@ApiOperation("Return nautical warnings of given status.")
  @RequestMapping(
      method = RequestMethod.GET,
      path = "/nautical-warnings/{status}",
      produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  @ResponseBody
  public ResponseEntity<?> nauticalWarnings(
      @ApiParam(value = "Status", required = true, allowableValues = "DRAFT,PUBLISHED,ARCHIVED")
          @PathVariable
          final String status) {
    final Status s = Status.valueOf(status.toUpperCase());
    final String url = String.format("%s?layer=%s", pookiUrl, s.layer);

    ResponseEntity<byte[]> response = template.getForEntity(url, byte[].class);

    if (RestUtil.isError(response.getStatusCode())) {
      response = template.getForEntity(url, byte[].class);
    }

    // Pooki unexpectedly returns body in GZip format, try to unzip it
    // If that fails, expect body to be "plain"
    byte[] body;
    try {
      body = decompress(response.getBody());
    } catch (final IOException e) {
      body = response.getBody();
    }

    if (RestUtil.isError(response.getStatusCode())) {
      return ResponseEntity.status(response.getStatusCode()).body(body);
    }

    return ResponseEntity.ok().body(body);
  }
  public Map<String, Map<String, List<String>>>
      getMapOfSenderAndRecieverValidationObjectivesWithReferenceFiles() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<GithubResponseWrapper> responseEntity =
        restTemplate.exchange(
            GITHUB_URL,
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<GithubResponseWrapper>() {});

    Map<String, Map<String, List<String>>> messageTypeValidationObjectiveReferenceFilesMap =
        new HashMap<>();
    for (TestDataTreeWrapper testDataTreeWrapper : responseEntity.getBody().getTree()) {
      if (!(testDataTreeWrapper.getPath().equalsIgnoreCase("license")
          || testDataTreeWrapper.getPath().equalsIgnoreCase("README.md"))) {
        if (isMessageTypeInMap(
            messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper)) {
          if (isValidationObjectiveInMap(
              messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper)) {
            addReferenceFileNameToListInValidationObjectiveMap(
                messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper);
          } else {
            addValidationObjectiveToMap(
                messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper);
          }
        } else {
          addMessageTypeToMap(messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper);
        }
      }
    }
    return messageTypeValidationObjectiveReferenceFilesMap;
  }
    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);
      }
    }
Exemple #4
0
  public static void main(String[] args) {
    RestTemplate restTemplate = new RestTemplate();
    String getAccessTokenUrl =
        String.format(
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
            PropertyHolder.APPID, PropertyHolder.APPSECRET);
    String retData =
        restTemplate.getForObject(getAccessTokenUrl, String.class, new HashMap<String, Object>());
    System.out.println("[Acess Token returned data] " + retData);

    JSONObject jsonObject = JSON.parseObject(retData);
    String accessToken = jsonObject.getString("access_token");
    String jsapiTicketUrl =
        String.format(
            "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",
            accessToken);
    retData =
        restTemplate.getForObject(jsapiTicketUrl, String.class, new HashMap<String, Object>());
    System.out.println("[jsapiTicketUrl returned data] " + retData);

    jsonObject = JSON.parseObject(retData);
    String jsapi_ticket = jsonObject.getString("ticket");

    String url = "http://cai.songdatech.com/crab/?buy_type=card";
    Map<String, String> ret = sign(jsapi_ticket, url);
    for (Map.Entry entry : ret.entrySet()) {
      System.out.println(entry.getKey() + ", " + entry.getValue());
    }
  }
  @Test
  public void loginWithOauth2Authentication() throws MalformedURLException {
    String token = "12345678";
    RestTemplate restTemplate = mock(RestTemplate.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    RestUtil restUtil = mock(RestUtil.class);
    OAuth2AccessToken oauthToken = mock(OAuth2AccessToken.class);
    when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class))).thenReturn(restTemplate);
    when(restUtil.createRequestFactory(any(HttpProxyConfiguration.class)))
        .thenReturn(clientHttpRequestFactory);
    when(restTemplate.getForObject(eq("http://api.cloud.me/info"), any(Class.class)))
        .thenReturn(INFO_WITH_AUTH);
    when(restUtil.createOauthClient(any(URL.class), any(HttpProxyConfiguration.class)))
        .thenReturn(new OauthClient(new URL("http://uaa.cloud.me"), restTemplate));
    when(restTemplate.execute(
            eq("http://uaa.cloud.me/oauth/authorize"),
            eq(HttpMethod.POST),
            any(RequestCallback.class),
            any(ResponseExtractor.class),
            any(Map.class)))
        .thenReturn(oauthToken);
    when(oauthToken.getValue()).thenReturn(token);
    when(oauthToken.getTokenType()).thenReturn("bearer");

    // Run Test
    CloudControllerClientFactory ccf = new CloudControllerClientFactory(restUtil, null);
    CloudControllerClient ccc =
        ccf.newCloudController(
            new URL("http://api.cloud.me"), new CloudCredentials("*****@*****.**", "passwd"), null);
    String loginToken = ccc.login();
    assertThat(loginToken, is("bearer " + token));
  }
  @Test
  public void loginWithNonOauthAuthentication() throws MalformedURLException {
    String token = "12345678";
    Map<String, String> tokenResponse = new HashMap<String, String>();
    tokenResponse.put("token", token);
    RestTemplate restTemplate = mock(RestTemplate.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    RestUtil restUtil = mock(RestUtil.class);
    when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class))).thenReturn(restTemplate);
    when(restUtil.createRequestFactory(any(HttpProxyConfiguration.class)))
        .thenReturn(clientHttpRequestFactory);
    when(restTemplate.getForObject(eq("http://api.cloud.me/info"), any(Class.class)))
        .thenReturn(INFO_WITHOUT_AUTH);
    when(restTemplate.postForObject(
            eq("http://api.cloud.me/users/{id}/tokens"),
            any(Object.class),
            any(Class.class),
            any(Object[].class)))
        .thenReturn(tokenResponse);

    // Run Test
    CloudControllerClientFactory ccf = new CloudControllerClientFactory(restUtil, null);
    CloudControllerClient ccc =
        ccf.newCloudController(
            new URL("http://api.cloud.me"), new CloudCredentials("*****@*****.**", "passwd"), null);
    String loginToken = ccc.login();
    assertThat(loginToken, is(token));
  }
  /**
   * Factory method for a secure RestTemplate with Basic authentication that does not follow
   * redirects, ignores cookies and does not throw exceptions on server side errors.
   *
   * @return a basic RestTemplate with Basic authentication
   */
  public static RestTemplate get(final String username, final String password) {

    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();

    if (username != null) {
      interceptors.add(
          new ClientHttpRequestInterceptor() {

            @Override
            public ClientHttpResponse intercept(
                HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                throws IOException {
              byte[] token = Base64.encode((username + ":" + password).getBytes());
              request.getHeaders().add("Authorization", "Basic " + new String(token));
              return execution.execute(request, body);
            }
          });
    }

    RestTemplate restTemplate =
        new RestTemplate(
            new InterceptingClientHttpRequestFactory(
                new SimpleClientHttpRequestFactory(), interceptors));
    if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) {
      new HttpComponentsCustomizer().customize(restTemplate);
    }
    restTemplate.setErrorHandler(
        new DefaultResponseErrorHandler() {
          @Override
          public void handleError(ClientHttpResponse response) throws IOException {}
        });
    return restTemplate;
  }
Exemple #8
0
  @Test
  public void invalidInput() {

    // create
    Task titleBlankTask = new Task();
    try {
      restTemplate.postForLocation(resourceUrl, titleBlankTask);
      fail("Create should fail while title is blank");
    } catch (HttpStatusCodeException e) {
      assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
      Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class);
      assertThat(messages).hasSize(1);
      assertThat(messages.get("title")).isIn("may not be empty", "不能为空");
    }

    // update
    titleBlankTask.setId(1L);
    try {
      restTemplate.put(resourceUrl + "/1", titleBlankTask);
      fail("Update should fail while title is blank");
    } catch (HttpStatusCodeException e) {
      assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
      Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class);
      assertThat(messages).hasSize(1);
      assertThat(messages.get("title")).isIn("may not be empty", "不能为空");
    }
  }
  @RequestMapping("/{userPseudo}/validateStep4")
  public ResponseEntity<Void> validateStep4(
      @PathVariable("userPseudo") String userPseudo,
      @RequestParam("userHostAndPort") String userHostAndPort) {
    log.info("Validation step 4 for player {} with data {}", userPseudo, userHostAndPort);

    ResponseEntity<Void> result = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);

    String url = "http://" + userHostAndPort + "/zen/env";

    ResponseEntity<String> responseEntityShouldFail =
        restTemplate.exchange(
            url, HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), String.class);

    byte[] encodedAuth = Base64.encodeBase64("zenika:technozaure".getBytes());
    String authHeader = "Basic " + new String(encodedAuth);

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", authHeader);
    HttpEntity<String> entity = new HttpEntity<>(headers);

    ResponseEntity<String> responseEntityShouldSucceed =
        restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

    if (responseEntityShouldFail.getStatusCode() != HttpStatus.OK
        && responseEntityShouldSucceed.getStatusCode() == HttpStatus.OK) {
      gameStepRepository.save(new GameStep(userPseudo, Step._4));
      result = new ResponseEntity<Void>(HttpStatus.OK);
      broadcastGameStatus();
    }

    return result;
  }
    @Override
    protected ItemGridModel[] doInBackground(Integer... args) {

      try {

        RestTemplate restTemplate = new RestTemplate();

        HttpComponentsClientHttpRequestFactory httpRequestFactory =
            new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(10 * 1000);
        httpRequestFactory.setReadTimeout(10 * 1000);
        restTemplate.setRequestFactory(httpRequestFactory);

        String url = Constant.URL_SERVICE;

        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        return restTemplate.getForObject(url, ItemGridModel[].class);
      } catch (ResourceAccessException e) {
        Log.e(Constant.TAG, "Error update grid", e);
      } catch (Exception e) {
        Log.e(Constant.TAG, "Error update grid", e);
      }
      return null;
    }
  @Override
  protected Object doInBackground(Object[] params) {
    try {
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

      HttpHeaders requestHeaders = new HttpHeaders();

      String restUrl = ServerConstants.SERVER_API_URL + "user/login";

      User user = new User(username, password);
      SingleUser singleUser = new SingleUser();
      singleUser.setUser(user);

      HttpEntity<SingleUser> requestEntity = new HttpEntity<>(singleUser, requestHeaders);

      ResponseEntity<Boolean> responseEntity =
          restTemplate.exchange(restUrl, HttpMethod.POST, requestEntity, Boolean.class);

      boolean loginSuccessful = responseEntity.getBody();

      Log.d("Login", Boolean.toString(loginSuccessful));

      return loginSuccessful;
    } catch (Exception ex) {
      ex.printStackTrace();

      return false;
    }
  }
  private void updateLastLoginDate(Integer id) throws ServiceException {

    RestTemplate restTemplate = this.restClient.getRestTemplate();
    String url = this.restClient.createServiceUrl("/auth/updatelogindate/" + id);

    HttpHeaders headers = this.restClient.getHttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<EmployeeDto> entity = new HttpEntity<EmployeeDto>(new EmployeeDto(), headers);

    MessageDto msg = null;
    try {
      msg = restTemplate.postForObject(url, entity, MessageDto.class);
    } catch (HttpStatusCodeException e) {
      MessageDto errorMsg = this.restClient.mapExceptionToMessage(e);

      if (errorMsg.hasFieldErrors()) {
        throw new ValidationException(errorMsg.getFieldErrors());
      } else {
        throw new ServiceException(errorMsg.getText());
      }
    } catch (RestClientException e) {
      throw new ServiceException("Could not publish news: " + e.getMessage(), e);
    }
  }
  @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;
  }
  public ArrayList getApplications(String keyword, UserDetails userDetails) {
    ArrayList applications = new ArrayList();
    Gson gson = new Gson();

    try {
      String urlString =
          "http://localhost:9093/prp-ws/hello/applications/"
              + keyword
              + "/"
              + userDetails.getUsername();
      RestTemplate restTemplate = new RestTemplate();
      String response = restTemplate.getForObject(urlString, String.class);

      Type listOfTestObject = new TypeToken<List<PrpAplctnEntity>>() {}.getType();
      ArrayList<PrpAplctnEntity> list = gson.fromJson(response, listOfTestObject);

      for (int i = 0; i < list.size(); i++) {
        applications.add(list.get(i));
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return applications;
  }
Exemple #15
0
    @Override
    protected Boolean doInBackground(HelpPost... arg0) {
      try {
        final String url =
            getMainApplication().getRestBaseUrl()
                + "/sendacceptnotification?"
                + "facebookId="
                + arg0[0].getUserId()
                + "&"
                + "firstName="
                + getMainApplication().getData("firstName")
                + "&"
                + "lastName="
                + getMainApplication().getData("lastName")
                + "&"
                + "postId="
                + arg0[0].getUserId()
                + "_"
                + arg0[0].getTime();

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
        return restTemplate.getForObject(new URI(url), Boolean.class);
      } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
      }
      return false;
    }
  @Override
  protected void onHandleIntent(Intent intent) {

    ApplicationController app = ((ApplicationController) getApplicationContext());
    UsuarioDTO user = app.getUserLogin();

    Map<String, Integer> parms = new HashMap<String, Integer>();
    parms.put("id", user.getId());

    restTemp.setErrorHandler(new RestResponseErrorHandler<String>(String.class));
    Intent intentBack = new Intent(Constantes.GET_AMIGOS_FILTRO_ACTION);

    try {

      UsuarioDTO[] respuesta =
          restTemp.getForObject(Constantes.GET_AMIGOS_SERVICE_URL, UsuarioDTO[].class, parms);

      intentBack.putExtra("respuesta", Util.getArrayListUsuarioDTO(respuesta));

    } catch (RestResponseException e) {
      String msg = e.getMensaje();
      intentBack.putExtra("error", msg);
    } catch (ResourceAccessException e) {
      Log.e(TAG, e.getMessage());
      intentBack.putExtra("error", Constantes.MSG_ERROR_TIMEOUT);
    }

    this.sendBroadcast(intentBack);
  }
  /**
   * Shutdown container by the given containerId.
   *
   * @throws NoSuchContainerException
   */
  @RequestMapping(value = "", method = RequestMethod.DELETE, params = "containerId")
  @ResponseStatus(HttpStatus.OK)
  public void shutdownContainer(String containerId)
      throws NoSuchContainerException, ContainerShutdownException {
    Container container = this.containerRepository.findOne(containerId);
    if (container != null) {
      String containerHost = container.getAttributes().getIp();
      String containerManagementPort = container.getAttributes().getManagementPort();
      RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
      try {
        restTemplate.postForObject(
            CONTAINER_HOST_URI_PROTOCOL
                + containerHost
                + ":"
                + containerManagementPort
                + managementContextPath
                + SHUTDOWN_ENDPOINT,
            Object.class,
            Object.class);

      } catch (RestClientException e) {
        throw new ContainerShutdownException(e.getMessage());
      }
    } else {
      throw new NoSuchContainerException("Container could not be found with id " + containerId);
    }
  }
Exemple #18
0
  /**
   * 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;
  }
Exemple #19
0
  /**
   * Gets the cloud ci.
   *
   * @param ns the ns
   * @param ciName the ci name
   * @return the cloud ci
   */
  public CmsCISimple getCloudCi(String ns, String ciName) {

    try {
      CmsCISimple[] mgmtClouds =
          restTemplate.getForObject(
              serviceUrl + "cm/simple/cis?nsPath={nsPath}&ciClassName={mgmtCloud}&ciName={ciName}",
              new CmsCISimple[0].getClass(),
              ns,
              mgmtCloud,
              ciName);
      if (mgmtClouds.length > 0) {
        return mgmtClouds[0];
      }
      CmsCISimple[] acctClouds =
          restTemplate.getForObject(
              serviceUrl + "cm/simple/cis?nsPath={nsPath}&ciClassName={acctCloud}&ciName={ciName}",
              new CmsCISimple[0].getClass(),
              ns,
              acctCloud,
              ciName);
      if (acctClouds.length > 0) {
        return acctClouds[0];
      }

      return null;
    } catch (RestClientException ce) {
      logger.error("Broker can not connect to cms api to authenticate the user:" + ce.getMessage());
      throw ce;
    }
  }
  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;
  }
  @Test
  public void testCreateZoneWithNonUniqueSubdomain() {
    IdentityZone idZone1 = new IdentityZone();
    String id1 = UUID.randomUUID().toString();
    idZone1.setId(id1);
    idZone1.setSubdomain(id1 + "non-unique");
    idZone1.setName("testCreateZone() " + id1);
    ResponseEntity<Void> response1 =
        client.exchange(
            serverRunning.getUrl("/identity-zones"),
            HttpMethod.POST,
            new HttpEntity<>(idZone1),
            new ParameterizedTypeReference<Void>() {},
            id1);
    assertEquals(HttpStatus.CREATED, response1.getStatusCode());

    IdentityZone idZone2 = new IdentityZone();
    String id2 = UUID.randomUUID().toString();
    idZone2.setId(id2);
    idZone2.setSubdomain(id1 + "non-unique");
    idZone2.setName("testCreateZone() " + id2);
    ResponseEntity<Map<String, String>> response2 =
        client.exchange(
            serverRunning.getUrl("/identity-zones"),
            HttpMethod.POST,
            new HttpEntity<>(idZone2),
            new ParameterizedTypeReference<Map<String, String>>() {},
            id2);
    assertEquals(HttpStatus.CONFLICT, response2.getStatusCode());
    Assert.assertTrue(
        response2.getBody().get("error_description").toLowerCase().contains("subdomain"));
  }
    @Override
    protected Message doInBackground(Void... params) {
      final String url = getString(R.string.base_uri) + "/getmessage";

      // Populate the HTTP Basic Authentitcation header with the username and password
      HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
      HttpHeaders requestHeaders = new HttpHeaders();
      requestHeaders.setAuthorization(authHeader);
      requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

      // Create a new RestTemplate instance
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

      try {
        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<Message> response =
            restTemplate.exchange(
                url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), Message.class);
        return response.getBody();
      } catch (HttpClientErrorException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        return new Message(0, e.getStatusText(), e.getLocalizedMessage());
      } catch (ResourceAccessException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        return new Message(0, e.getClass().getSimpleName(), e.getLocalizedMessage());
      }
    }
  @Test
  public void loginWithWrongPassword() throws MalformedURLException {
    thrown.expect(CloudFoundryException.class);
    RestTemplate restTemplate = mock(RestTemplate.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    RestUtil restUtil = mock(RestUtil.class);
    when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class))).thenReturn(restTemplate);
    when(restUtil.createRequestFactory(any(HttpProxyConfiguration.class)))
        .thenReturn(clientHttpRequestFactory);
    when(restTemplate.getForObject(eq("http://api.cloud.me/info"), any(Class.class)))
        .thenReturn(INFO_WITH_AUTH);
    when(restUtil.createOauthClient(any(URL.class), any(HttpProxyConfiguration.class)))
        .thenReturn(new OauthClient(new URL("http://uaa.cloud.me"), restTemplate));
    when(restTemplate.execute(
            eq("http://uaa.cloud.me/oauth/authorize"),
            eq(HttpMethod.POST),
            any(RequestCallback.class),
            any(ResponseExtractor.class),
            any(Map.class)))
        .thenThrow(
            new CloudFoundryException(HttpStatus.UNAUTHORIZED, "Error requesting access token."));

    // Run Test
    CloudControllerClientFactory ccf = new CloudControllerClientFactory(restUtil, null);
    CloudControllerClient ccc =
        ccf.newCloudController(
            new URL("http://api.cloud.me"),
            new CloudCredentials("*****@*****.**", "badpasswd"),
            null);
    ccc.login();
  }
  public String registerStudy(String studyOid, String hostName) {
    String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid;
    String pManageUrl =
        CoreResources.getField("portalURL")
            + "/app/rest/oc/authorizations?studyoid="
            + studyOid
            + "&instanceurl="
            + ocUrl;
    Authorization authRequest = new Authorization();
    Study authStudy = new Study();
    authStudy.setStudyOid(studyOid);
    authStudy.setInstanceUrl(ocUrl);
    authStudy.setHost(hostName);
    authRequest.setStudy(authStudy);

    CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
    requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT);
    RestTemplate rest = new RestTemplate(requestFactory);

    try {
      Authorization response = rest.postForObject(pManageUrl, authRequest, Authorization.class);
      if (response != null && response.getAuthorizationStatus() != null)
        return response.getAuthorizationStatus().getStatus();
    } catch (Exception e) {
      logger.error(e.getMessage());
      logger.error(ExceptionUtils.getStackTrace(e));
    }
    return "";
  }
  /**
   * Adapter for spotify's lookup api
   *
   * @param spotifyId - id of track, has to start with "spotify:track:"
   * @return Track with given id
   * @throws SpotifyApiException - Error contacting spotify,
   * @throws IllegalArgumentException - Is thrown when trying to fetch data that isn't a track
   */
  private SpotifyLookupContainer requestSpotifySong(String spotifyId) throws SpotifyApiException {
    RestTemplate rest = new RestTemplate();
    SpotifyLookupContainer response = null;

    if (spotifyId.indexOf("spotify:track:")
        != 0) { // trying to look up something that isn't a track
      throw new IllegalArgumentException();
    }

    try {
      logger.debug("Fetching spotifysong with uri: " + spotifyId);
      String jsonResponse =
          rest.getForObject("http://ws.spotify.com/lookup/1/.json?uri=" + spotifyId, String.class);
      response =
          gson.fromJson(
              jsonResponse,
              SpotifyLookupContainer
                  .class); // use gson rather than built in spring deserializer which needs the
      // object to match all fields
      if (!isPlayable(response.getTrack())) {
        logger.debug(
            "Song " + response.getTrack().getName() + " is not playable in Norway, ignoring");
        throw new IllegalArgumentException("Song not playable in Norway");
      }

    } catch (RestClientException e) {
      logger.error(
          "Exception while fetching spotifySong " + spotifyId + " error: " + e.getMessage());
      throw new SpotifyApiException(e.getMessage());
    }
    return response;
  }
  public String getStudyHost(String studyOid) throws Exception {

    String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid;
    String pManageUrl = CoreResources.getField("portalURL");
    String pManageUrlFull =
        pManageUrl + "/app/rest/oc/authorizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl;

    CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
    requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT);
    RestTemplate rest = new RestTemplate(requestFactory);
    try {
      Authorization[] response = rest.getForObject(pManageUrlFull, Authorization[].class);
      if (response.length > 0
          && response[0].getStudy() != null
          && response[0].getStudy().getHost() != null
          && !response[0].getStudy().getHost().equals("")) {
        URL url = new URL(pManageUrl);
        String port = "";
        if (url.getPort() > 0) port = ":" + String.valueOf(url.getPort());
        return url.getProtocol()
            + "://"
            + response[0].getStudy().getHost()
            + "."
            + url.getHost()
            + port
            + "/#/login";
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      logger.error(ExceptionUtils.getStackTrace(e));
    }
    return "";
  }
    private TermList getTermlist() {
      // TODO Auto-generated method stub
      MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
      ResponseEntity<TermList> responseEntity = null;

      HttpHeaders requestHeaders = new HttpHeaders();
      requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "xml")));
      HttpEntity<?> requestEntity = new HttpEntity<Object>(body, requestHeaders);

      String newurl = "http://www.dcapp.org/export/category.xml";

      try {
        RestTemplate restTemplate = new DCAppRestTemplate(10000);
        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(this.url, HttpMethod.POST, requestEntity,
        // TermList.class);
        responseEntity =
            restTemplate.exchange(newurl, HttpMethod.GET, requestEntity, TermList.class);
      } catch (RestClientException e) {
        Log.e("DirectoryFragment", "Exception while retrieving terms listing.", e.getCause());
      }

      TermList terms = responseEntity.getBody();

      terms.setIsParent();

      return terms;
    }
 public static void createDoctorListByAdmin() throws JsonProcessingException {
   // speciality.setId(2);
   // doctor.setSpeciality(speciality);
   ObjectMapper mapper = new ObjectMapper();
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   List<Integer> ids = new ArrayList<>();
   ids.add(17);
   ids.add(18);
   doctor.setInstitutionIds(ids);
   doctor2.setInstitutionIds(ids);
   List<Doctor> list = new ArrayList<>();
   list.add(doctor);
   list.add(doctor2);
   HttpEntity entity = new HttpEntity(list, headers);
   // System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity.getBody()));
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.CREATE_DOCTOR_LIST_URI, HttpMethod.POST, entity, Response.class);
   mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity.getBody()));
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
 private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
   String baseUrl = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort();
   RestTemplate rest = new TestRestTemplate();
   // First, verify the web endpoint can't be reached
   assertEndpointUnauthorized(baseUrl, rest);
   // Since we can't reach it, need to collect an authorization token
   HttpHeaders headers = getHeaders(config);
   String url = baseUrl + "/oauth/token";
   JsonNode tokenResponse =
       rest.postForObject(
           url, new HttpEntity<MultiValueMap<String, Object>>(getBody(), headers), JsonNode.class);
   String authorizationToken = tokenResponse.findValue("access_token").asText();
   String tokenType = tokenResponse.findValue("token_type").asText();
   String scope = tokenResponse.findValues("scope").get(0).toString();
   assertThat(tokenType, equalTo("bearer"));
   assertThat(scope, equalTo("\"read\""));
   // Now we should be able to see that endpoint.
   headers.set("Authorization", "BEARER " + authorizationToken);
   ResponseEntity<String> securedResponse =
       rest.exchange(
           new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")),
           String.class);
   assertThat(securedResponse.getStatusCode(), equalTo(HttpStatus.OK));
   assertThat(
       securedResponse.getBody(),
       equalTo("You reached an endpoint " + "secured by Spring Security OAuth2"));
   ResponseEntity<String> entity =
       rest.exchange(
           new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")),
           String.class);
   assertThat(entity.getStatusCode(), equalTo(finalStatus));
 }
  @Override
  protected Integer doInBackground(String... params) {
    try {
      try {
        username = params[0];
        password = params[1];
        String url =
            "http://"
                + WS_IP
                + "/myresource/registermobile?username="******"&password="******"Myapp", "username = "******"  password= "******" response text=" + s);

        return code;
      } catch (Exception e) {
        errordetails = e.getMessage();
        return 500;
      }
    } catch (Exception e) {
      Log.e("HttpRequestTask", e.getMessage(), e);
      return 500;
    }
  }