/**
   * 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);
    }
  }
    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);
      }
    }
  public JSONObject show(String id) {
    setLastRestErrorCode(HttpStatus.OK);

    // nested url = bets/:bet_id/predictions
    String res = null;
    try {
      res =
          restTemplate.getForObject(
              url + "/" + id + ".json?" + GetURLTokenParam(), String.class, getServerBet_id());
    } catch (HttpClientErrorException e) {
      setLastRestErrorCode(e.getStatusCode());
      return null;
    } catch (RestClientException e) {
      e.printStackTrace();
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
      return null;
    }

    JSONObject json = null;
    try {
      json = new JSONObject(res);
    } catch (JSONException e) {
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
      e.printStackTrace();
    }

    return json;
  }
Example #4
0
  private Remembered checkSession(
      final String sessionId, HttpServletRequest request, HttpServletResponse response) {
    try {
      SimpleClientHttpRequestFactory tokenExtender =
          new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod)
                throws IOException {
              super.prepareConnection(connection, httpMethod);

              connection.setRequestProperty("Authorization", "Bearer " + sessionId);
              connection.setRequestProperty("Accept", "application/json");
              connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }
          };

      String userResponse =
          new RestTemplate(tokenExtender).getForObject(userDetailsUri, String.class);

      return makeNewRemembered(
          Json.read(userResponse).asJsonMap().get("username").asString(), sessionId);
    } catch (RestClientException ex) {
      // TODO: обработать исключение - записать в лог и т.д. - потенциально ошибки соединения с
      // сайтом авторизации, ошибки авторизации
      System.out.println(
          "GOT exception: "
              + ex
                  .toString()); // <-- не делайте так на боевом сервере, используйте
                                // java.util.Logger
      if (ex instanceof HttpClientErrorException)
        System.out.println(
            "response: " + ((HttpClientErrorException) ex).getResponseBodyAsString());
      return null;
    }
  }
Example #5
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;
    }
  }
Example #6
0
  /**
   * 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;
  }
  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);
    }
  }
    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;
    }
  @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 JSONArray showUpdatesForBet(String bet_id, DateTime lastUpdate) {
    setLastRestErrorCode(HttpStatus.OK);

    // nested url = bets/:bet_id/chat_messages
    String res;
    try {
      res =
          restTemplate.getForObject(
              url
                  + "/show_updates_for_bet.json?"
                  + GetURLTokenParam()
                  + "&updated_at="
                  + lastUpdate,
              String.class,
              bet_id);
    } catch (HttpClientErrorException e) {
      setLastRestErrorCode(e.getStatusCode());
      return null;
    } catch (RestClientException e) {
      e.printStackTrace();
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
      return null;
    }

    JSONArray json = null;
    try {
      json = new JSONArray(res);
    } catch (JSONException e) {
      e.printStackTrace();
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return json;
  }
  public JSONObject create(ChatMessage chatMessage) {
    setLastRestErrorCode(HttpStatus.CREATED);

    JSONObject json = chatMessage.toJson();

    // nested url = bets/:bet_id/predictions
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("X-AUTH-TOKEN", GetToken());
    HttpEntity request = new HttpEntity(json.toString(), headers);
    String res;
    try {
      res = restTemplate.postForObject(url + ".json", request, String.class, getServerBet_id());
    } catch (HttpClientErrorException e) {
      setLastRestErrorCode(e.getStatusCode());
      return null;
    } catch (RestClientException e) {
      e.printStackTrace();
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
      return null;
    }

    JSONObject jsonRes = null;
    try {
      jsonRes = new JSONObject(res);
    } catch (JSONException e) {
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
      e.printStackTrace();
    }

    return jsonRes;
  }
 @Override
 protected <T> T doExecute(
     URI url,
     HttpMethod method,
     RequestCallback requestCallback,
     final ResponseExtractor<T> responseExtractor)
     throws RestClientException {
   final String[] status = new String[1];
   final HttpStatus[] httpStatus = new HttpStatus[1];
   final Object[] headers = new Object[1];
   final String[] message = new String[1];
   T results = null;
   RestClientException exception = null;
   try {
     results =
         super.doExecute(
             url,
             method,
             requestCallback,
             new ResponseExtractor<T>() {
               @SuppressWarnings("rawtypes")
               public T extractData(ClientHttpResponse response) throws IOException {
                 httpStatus[0] = response.getStatusCode();
                 headers[0] = response.getHeaders();
                 T data = null;
                 if (responseExtractor != null
                     && (data = responseExtractor.extractData(response)) != null) {
                   if (data instanceof String) {
                     message[0] = ((String) data).length() + " bytes";
                   } else if (data instanceof Map) {
                     message[0] = ((Map) data).keySet().toString();
                   } else {
                     message[0] = data.getClass().getName();
                   }
                   return data;
                 } else {
                   message[0] = "<no data>";
                   return null;
                 }
               }
             });
     status[0] = "OK";
   } catch (RestClientException e) {
     status[0] = "ERROR";
     message[0] = e.getMessage();
     exception = e;
     if (e instanceof HttpStatusCodeException) {
       httpStatus[0] = ((HttpStatusCodeException) e).getStatusCode();
     }
   }
   addLogMessage(method, url, status[0], httpStatus[0], message[0]);
   if (exception != null) {
     throw exception;
   }
   return results;
 }
Example #13
0
 /**
  * Gets transport positions from helsinki webservice <br>
  * Sample output: CEENG1074300234;1008;24.9059;60.1631;121;1;0;1201433;1200;1;HKL;84 ID transport
  * ; line ; longitude ; latitude ; orientation If ID transport starts with 'C' -> Train If ID
  * transport starts with 'E' -> Bus
  */
 private String getTransportPositions() {
   try {
     return restTemplate.getForEntity(URL, String.class).getBody();
   } catch (RestClientException e) {
     logger.error(
         "Error getting position information from Helsinki external service. " + e.getMessage(),
         e);
     throw e;
   }
 }
 @SuppressWarnings("finally")
 public Account signup(Account account) {
   Account respAccount = null;
   try {
     respAccount = restTemplate.postForObject(serviceUrl + "/signup", account, Account.class);
   } catch (RestClientException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } finally {
     return respAccount;
   }
 }
  public void delete(String id) {
    setLastRestErrorCode(HttpStatus.OK);

    try {
      restTemplate.delete(url + "/" + id + ".json?" + GetURLTokenParam(), getServerBet_id(), id);
    } catch (HttpClientErrorException e) {
      setLastRestErrorCode(e.getStatusCode());
    } catch (RestClientException e) {
      e.printStackTrace();
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
 /**
  * List all the available containers along with the message rates for each deployed modules.
  *
  * @throws ModuleMessageRateNotFoundException
  * @throws JSONException
  */
 @RequestMapping(value = "", method = RequestMethod.GET)
 @ResponseStatus(HttpStatus.OK)
 @ResponseBody
 public PagedResources<DetailedContainerResource> list(
     Pageable pageable, PagedResourcesAssembler<DetailedContainer> assembler)
     throws ModuleMessageRateNotFoundException, JSONException {
   Page<DetailedContainer> containers = containerRepository.findAllRuntimeContainers(pageable);
   for (DetailedContainer container : containers) {
     String containerHost = container.getAttributes().getIp();
     String containerManagementPort = container.getAttributes().getManagementPort();
     if (StringUtils.hasText(containerManagementPort)
         && enableMessageRates.equalsIgnoreCase("true")) {
       Map<String, HashMap<String, Double>> messageRates =
           new HashMap<String, HashMap<String, Double>>();
       for (ModuleMetadata moduleMetadata : container.getDeployedModules()) {
         String moduleName = moduleMetadata.getName();
         String moduleLabel = moduleName.substring(0, moduleName.indexOf('.'));
         String request =
             CONTAINER_HOST_URI_PROTOCOL
                 + containerHost
                 + ":"
                 + containerManagementPort
                 + "/management/jolokia/read/xd."
                 + moduleMetadata.getUnitName()
                 + ":module="
                 + moduleLabel
                 + ".*,component=*,name=%s/MeanSendRate";
         try {
           HashMap<String, Double> rate = new HashMap<String, Double>();
           if (moduleMetadata.getModuleType().equals(ModuleType.source)) {
             rate.put("output", getMessageRate(String.format(request, "output")));
           } else if (moduleMetadata.getModuleType().equals(ModuleType.sink)) {
             rate.put("input", getMessageRate(String.format(request, "input")));
           } else if (moduleMetadata.getModuleType().equals(ModuleType.processor)) {
             rate.put("output", getMessageRate(String.format(request, "output")));
             rate.put("input", getMessageRate(String.format(request, "input")));
           }
           messageRates.put(moduleMetadata.getQualifiedId(), rate);
         } catch (RestClientException e) {
           throw new ModuleMessageRateNotFoundException(e.getMessage());
         }
       }
       container.setMessageRates(messageRates);
     }
   }
   return assembler.toResource(containers, resourceAssembler);
 }
Example #17
0
  private String finishSessionRetrieval(HttpServletRequest request)
      throws UnsupportedEncodingException {
    try {
      String authCode = request.getParameter("code");
      SimpleClientHttpRequestFactory serviceAuthExtender =
          new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod)
                throws IOException {
              super.prepareConnection(connection, httpMethod);

              String authorization = clientId + ":" + clientSecret;
              byte[] encodedAuthorisation = Base64.encode(authorization.getBytes());
              connection.setRequestProperty(
                  "Authorization", "Basic " + new String(encodedAuthorisation));
              connection.setRequestProperty(
                  "Accept", "application/json, application/x-www-form-urlencoded");
              connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }
          };

      String tokenRequest =
          "grant_type=authorization_code&code="
              + authCode
              + "&redirect_uri="
              + URLEncoder.encode(request.getRequestURL().toString(), "utf-8");
      String tokenResponse =
          new RestTemplate(serviceAuthExtender)
              .postForObject(URI.create(accessTokenUri), tokenRequest, String.class);

      return Json.read(tokenResponse).asJsonMap().get("access_token").asString();
    } catch (RestClientException ex) {
      // TODO: обработать исключение - записать в лог и т.д. - потенциально ошибки соединения с
      // сайтом авторизации, ошибки авторизации
      System.out.println(
          "GOT exception: "
              + ex
                  .toString()); // <-- не делайте так на боевом сервере, используйте
                                // java.util.Logger
      if (ex instanceof HttpClientErrorException)
        System.out.println(
            "response: " + ((HttpClientErrorException) ex).getResponseBodyAsString());
      return null;
    }
  }
  public void update(ChatMessage chatMessage, String id) {
    setLastRestErrorCode(HttpStatus.OK);

    JSONObject json = chatMessage.toJson();

    // nested url = bets/:bet_id/predictions
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("X-AUTH-TOKEN", GetToken());
    HttpEntity request = new HttpEntity(json.toString(), headers);
    try {
      restTemplate.put(url + "/" + id + ".json", request, getServerBet_id());
    } catch (HttpClientErrorException e) {
      setLastRestErrorCode(e.getStatusCode());
    } catch (RestClientException e) {
      e.printStackTrace();
      setLastRestErrorCode(HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
Example #19
0
  /**
   * _get zone ci.
   *
   * @param ns the ns
   * @param ciName the ci name
   * @return the cms ci simple
   */
  public CmsCISimple _getZoneCi(String ns, String ciName) {

    try {
      CmsCISimple[] cis =
          restTemplate.getForObject(
              serviceUrl + "cm/simple/cis?nsPath={nsPath}&ciClassName={zoneClass}&ciName={ciName}",
              new CmsCISimple[0].getClass(),
              ns,
              zoneClass,
              ciName);
      if (cis.length > 0) {
        return cis[0];
      }
      ;
      return null;
    } catch (RestClientException ce) {
      logger.error("Broker can not connect to cms api to authenticate the user:" + ce.getMessage());
      throw ce;
    }
  }
  @Background
  void sendAuthRequest(SingupRequestEntity requestEntity) {

    try {
      TokenResponseEntity response = restClient.authSignupUser(requestEntity);

      if (response == null) {
        showErrorNotification("sign up fail");
        return;
      }

      Log.w(TAG, "token: " + response.getToken());
      prefs.edit().bookfusionAccessToken().put(response.getToken()).apply();

      ProfileDataResponseEntity profile =
          restClient.getProfileData(
              CommonUtils.getDeviceID(getActivity()), prefs.bookfusionAccessToken().get());
      prefs.edit().currentUserId().put(profile.getId()).apply();

      showSignInNotification();

    } catch (RestClientException clientException) {
      HttpStatus status = null;
      if (clientException instanceof HttpClientErrorException) {
        status = ((HttpClientErrorException) clientException).getStatusCode();
      } else if (clientException instanceof HttpServerErrorException) {
        status = ((HttpServerErrorException) clientException).getStatusCode();
      }

      String errorMessage;
      if (status != null) {
        errorMessage = HttpUtils.getHttpErrorMessage(status.toString());
      } else {
        errorMessage = "Error happened, try again please";
      }

      showErrorNotification(errorMessage);
      Log.e(TAG, "Error happened: " + clientException.getMessage());
    }
  }
Example #21
0
  /**
   * Adapter for spotify's search api
   *
   * @param query - to match tracks
   * @param page - what page with results to see
   * @return Tracks matching query
   * @throws SpotifyApiException - Error contacting spotify
   */
  private SpotifyTrackSearchContainer searchSpotify(String query, int page)
      throws SpotifyApiException {
    RestTemplate rest = new RestTemplate();
    SpotifyTrackSearchContainer response = null;

    try {
      logger.debug("Searching for spotify-songs with query " + query);
      String jsonResponse =
          rest.getForObject(
              "http://ws.spotify.com/search/1/track.json?q=" + query + "&page=" + page,
              String.class);
      response = gson.fromJson(jsonResponse, SpotifyTrackSearchContainer.class);

      for (int i = response.getTracks().size() - 1;
          i >= 0;
          i--) { // remove songs from result that cannot be played in norway
        if (!isPlayable(response.getTracks().get(i))) {
          logger.debug(
              "Song "
                  + response.getTracks().get(i).getName()
                  + " is not playable in Norway, ignoring");
          response.getTracks().remove(i);
        }
      }
    } catch (RestClientException e) {
      logger.error(
          "Exception while searching for spotifysongs matching "
              + query
              + " error: "
              + e.getMessage());
      throw new SpotifyApiException(e.getMessage());
    } catch (JsonSyntaxException e) {
      logger.error(
          "Error reading response from spotify: " + response + " error: " + e.getMessage());
      throw new SpotifyApiException(e.getMessage());
    }
    return response;
  }
  @Override
  public void logout() throws ServiceException {
    RestTemplate restTemplate = this.restClient.getRestTemplate();
    String url = this.restClient.createServiceUrl("/logout");

    LOG.info("Logout " + this.user.getUsername() + " at " + url);

    UserStatusDto status = null;
    try {
      this.updateLastLoginDate(this.user.getId());
      status = restTemplate.getForObject(url, UserStatusDto.class);
    } catch (RestClientException e) {
      throw new ServiceException("Logout failed: " + e.getMessage(), e);
    }

    if (status.getEvent() != UserEvent.LOGOUT) {
      throw new ServiceException("Logout failed: Invalid event");
    } else {
      LOG.debug("Logout " + this.user.getUsername() + " successful");
    }

    this.user = new UserStatusDto();
  }
Example #23
0
  @RequestMapping(value = "/doQuit", method = RequestMethod.POST)
  public ModelAndView doQuit(@Valid HelloModel helloModel, BindingResult bindingResult) {
    ApplicationContext context =
        new ClassPathXmlApplicationContext("controller/webservice/spring.xml");
    String ERROR = (String) context.getBean("ERROR");

    List<FieldError> feeErrors = new ArrayList<FieldError>();

    if (bindingResult.hasErrors()) {
      return new ModelAndView(ERROR, "ErrorModel", bindingResult.getFieldErrors());
    }

    String fee_service = (String) context.getBean("fee_service");
    String fee_provider = fee_service.split("/")[3].split("_")[0];

    String name = helloModel.getName();

    FeeModel feeModel = (FeeModel) context.getBean("feeModel");
    feeModel.setName(name);

    int count;

    try {
      try {
        feeModel =
            restTemplate.getForObject(
                new StringBuilder(fee_service)
                    .append("/findByName?name=")
                    .append(feeModel.getName())
                    .toString(),
                FeeModel.class);
      } catch (RestClientException restClientException) {
        String statusCode = restClientException.getMessage();

        if (statusCode.equals("404 Not Found")) {
          throw new NullAccountException();
        } else {
          throw restClientException;
        }
      }

      count = feeModel.getCount();

      if (count > 0) {
        throw new FeeNotPaidException();
      } else if (count == 0) {
        restTemplate.delete(
            new StringBuilder(fee_service).append("/").append(feeModel.getId()).toString());
      }
    } catch (NullAccountException e) {
      feeErrors.add(
          new FieldError("QuitController", e.getMessage(), resource.getString(e.getMessage())));
      return new ModelAndView(ERROR, "ErrorModel", feeErrors);
    } catch (FeeNotPaidException e) {
      feeErrors.add(
          new FieldError("QuitController", e.getMessage(), resource.getString(e.getMessage())));
      return new ModelAndView(ERROR, "ErrorModel", feeErrors);
    } catch (RestClientException e) {
      feeErrors.add(
          new FieldError(
              "QuitController",
              "error.http",
              resource.getString("error.http") + "<br>" + e.getMessage()));
      return new ModelAndView(ERROR, "ErrorModel", feeErrors);
    } catch (Exception e) {
      feeErrors.add(
          new FieldError(
              "QuitController",
              "error.database",
              resource.getString("error.database") + "<br>" + e.getMessage()));
      return new ModelAndView(ERROR, "ErrorModel", feeErrors);
    }

    FeeProviderModel feeProviderModel = (FeeProviderModel) context.getBean("feeProviderModel");
    feeProviderModel.setFeeModel(feeModel);
    feeProviderModel.setFeeProvider(fee_provider);

    String SUCCESS = (String) context.getBean("quitSUCCESS");
    return new ModelAndView(SUCCESS, "FeeProviderModel", feeProviderModel);
  }
  /**
   * @param request The request from which to extract parameters and perform the authentication
   * @return The authenticated user token, or null if authentication is incomplete.
   */
  protected Authentication handleAuthorizationCodeResponse(
      HttpServletRequest request, HttpServletResponse response) {

    String authorizationCode = request.getParameter("code");

    HttpSession session = request.getSession();

    // check for state, if it doesn't match we bail early
    String storedState = getStoredState(session);
    if (!Strings.isNullOrEmpty(storedState)) {
      String state = request.getParameter("state");
      if (!storedState.equals(state)) {
        throw new AuthenticationServiceException(
            "State parameter mismatch on return. Expected " + storedState + " got " + state);
      }
    }

    // look up the issuer that we set out to talk to
    String issuer = getStoredSessionString(session, ISSUER_SESSION_VARIABLE);

    // pull the configurations based on that issuer
    ServerConfiguration serverConfig = servers.getServerConfiguration(issuer);
    final RegisteredClient clientConfig = clients.getClientConfiguration(serverConfig);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add("grant_type", "authorization_code");
    form.add("code", authorizationCode);
    form.setAll(authOptions.getTokenOptions(serverConfig, clientConfig, request));

    String redirectUri = getStoredSessionString(session, REDIRECT_URI_SESION_VARIABLE);
    if (redirectUri != null) {
      form.add("redirect_uri", redirectUri);
    }

    // Handle Token Endpoint interaction

    HttpClient httpClient =
        HttpClientBuilder.create()
            .useSystemProperties()
            .setDefaultRequestConfig(
                RequestConfig.custom().setSocketTimeout(httpSocketTimeout).build())
            .build();

    HttpComponentsClientHttpRequestFactory factory =
        new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate;

    if (SECRET_BASIC.equals(clientConfig.getTokenEndpointAuthMethod())) {
      // use BASIC auth if configured to do so
      restTemplate =
          new RestTemplate(factory) {

            @Override
            protected ClientHttpRequest createRequest(URI url, HttpMethod method)
                throws IOException {
              ClientHttpRequest httpRequest = super.createRequest(url, method);
              httpRequest
                  .getHeaders()
                  .add(
                      "Authorization",
                      String.format(
                          "Basic %s",
                          Base64.encode(
                              String.format(
                                  "%s:%s",
                                  UriUtils.encodePathSegment(clientConfig.getClientId(), "UTF-8"),
                                  UriUtils.encodePathSegment(
                                      clientConfig.getClientSecret(), "UTF-8")))));

              return httpRequest;
            }
          };
    } else {
      // we're not doing basic auth, figure out what other flavor we have
      restTemplate = new RestTemplate(factory);

      if (SECRET_JWT.equals(clientConfig.getTokenEndpointAuthMethod())
          || PRIVATE_KEY.equals(clientConfig.getTokenEndpointAuthMethod())) {
        // do a symmetric secret signed JWT for auth

        JWTSigningAndValidationService signer = null;
        JWSAlgorithm alg = clientConfig.getTokenEndpointAuthSigningAlg();

        if (SECRET_JWT.equals(clientConfig.getTokenEndpointAuthMethod())
            && (alg.equals(JWSAlgorithm.HS256)
                || alg.equals(JWSAlgorithm.HS384)
                || alg.equals(JWSAlgorithm.HS512))) {

          // generate one based on client secret
          signer = symmetricCacheService.getSymmetricValidtor(clientConfig.getClient());

        } else if (PRIVATE_KEY.equals(clientConfig.getTokenEndpointAuthMethod())) {

          // needs to be wired in to the bean
          signer = authenticationSignerService;

          if (alg == null) {
            alg = authenticationSignerService.getDefaultSigningAlgorithm();
          }
        }

        if (signer == null) {
          throw new AuthenticationServiceException(
              "Couldn't find required signer service for use with private key auth.");
        }

        JWTClaimsSet claimsSet = new JWTClaimsSet();

        claimsSet.setIssuer(clientConfig.getClientId());
        claimsSet.setSubject(clientConfig.getClientId());
        claimsSet.setAudience(Lists.newArrayList(serverConfig.getTokenEndpointUri()));
        claimsSet.setJWTID(UUID.randomUUID().toString());

        // TODO: make this configurable
        Date exp = new Date(System.currentTimeMillis() + (60 * 1000)); // auth good for 60 seconds
        claimsSet.setExpirationTime(exp);

        Date now = new Date(System.currentTimeMillis());
        claimsSet.setIssueTime(now);
        claimsSet.setNotBeforeTime(now);

        JWSHeader header =
            new JWSHeader(
                alg,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                signer.getDefaultSignerKeyId(),
                null,
                null);
        SignedJWT jwt = new SignedJWT(header, claimsSet);

        signer.signJwt(jwt, alg);

        form.add("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
        form.add("client_assertion", jwt.serialize());
      } else {
        // Alternatively use form based auth
        form.add("client_id", clientConfig.getClientId());
        form.add("client_secret", clientConfig.getClientSecret());
      }
    }

    logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointUri());
    logger.debug("form = " + form);

    String jsonString = null;

    try {
      jsonString =
          restTemplate.postForObject(serverConfig.getTokenEndpointUri(), form, String.class);
    } catch (RestClientException e) {

      // Handle error

      logger.error("Token Endpoint error response:  " + e.getMessage());

      throw new AuthenticationServiceException("Unable to obtain Access Token: " + e.getMessage());
    }

    logger.debug("from TokenEndpoint jsonString = " + jsonString);

    JsonElement jsonRoot = new JsonParser().parse(jsonString);
    if (!jsonRoot.isJsonObject()) {
      throw new AuthenticationServiceException(
          "Token Endpoint did not return a JSON object: " + jsonRoot);
    }

    JsonObject tokenResponse = jsonRoot.getAsJsonObject();

    if (tokenResponse.get("error") != null) {

      // Handle error

      String error = tokenResponse.get("error").getAsString();

      logger.error("Token Endpoint returned: " + error);

      throw new AuthenticationServiceException(
          "Unable to obtain Access Token.  Token Endpoint returned: " + error);

    } else {

      // Extract the id_token to insert into the
      // OIDCAuthenticationToken

      // get out all the token strings
      String accessTokenValue = null;
      String idTokenValue = null;
      String refreshTokenValue = null;

      if (tokenResponse.has("access_token")) {
        accessTokenValue = tokenResponse.get("access_token").getAsString();
      } else {
        throw new AuthenticationServiceException(
            "Token Endpoint did not return an access_token: " + jsonString);
      }

      if (tokenResponse.has("id_token")) {
        idTokenValue = tokenResponse.get("id_token").getAsString();
      } else {
        logger.error("Token Endpoint did not return an id_token");
        throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
      }

      if (tokenResponse.has("refresh_token")) {
        refreshTokenValue = tokenResponse.get("refresh_token").getAsString();
      }

      try {
        JWT idToken = JWTParser.parse(idTokenValue);

        // validate our ID Token over a number of tests
        ReadOnlyJWTClaimsSet idClaims = idToken.getJWTClaimsSet();

        // check the signature
        JWTSigningAndValidationService jwtValidator = null;

        Algorithm tokenAlg = idToken.getHeader().getAlgorithm();

        Algorithm clientAlg = clientConfig.getIdTokenSignedResponseAlg();

        if (clientAlg != null) {
          if (!clientAlg.equals(tokenAlg)) {
            throw new AuthenticationServiceException(
                "Token algorithm " + tokenAlg + " does not match expected algorithm " + clientAlg);
          }
        }

        if (idToken instanceof PlainJWT) {

          if (clientAlg == null) {
            throw new AuthenticationServiceException(
                "Unsigned ID tokens can only be used if explicitly configured in client.");
          }

          if (tokenAlg != null && !tokenAlg.equals(Algorithm.NONE)) {
            throw new AuthenticationServiceException(
                "Unsigned token received, expected signature with " + tokenAlg);
          }
        } else if (idToken instanceof SignedJWT) {

          SignedJWT signedIdToken = (SignedJWT) idToken;

          if (tokenAlg.equals(JWSAlgorithm.HS256)
              || tokenAlg.equals(JWSAlgorithm.HS384)
              || tokenAlg.equals(JWSAlgorithm.HS512)) {

            // generate one based on client secret
            jwtValidator = symmetricCacheService.getSymmetricValidtor(clientConfig.getClient());
          } else {
            // otherwise load from the server's public key
            jwtValidator = validationServices.getValidator(serverConfig.getJwksUri());
          }

          if (jwtValidator != null) {
            if (!jwtValidator.validateSignature(signedIdToken)) {
              throw new AuthenticationServiceException("Signature validation failed");
            }
          } else {
            logger.error("No validation service found. Skipping signature validation");
            throw new AuthenticationServiceException(
                "Unable to find an appropriate signature validator for ID Token.");
          }
        } // TODO: encrypted id tokens

        // check the issuer
        if (idClaims.getIssuer() == null) {
          throw new AuthenticationServiceException("Id Token Issuer is null");
        } else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())) {
          throw new AuthenticationServiceException(
              "Issuers do not match, expected "
                  + serverConfig.getIssuer()
                  + " got "
                  + idClaims.getIssuer());
        }

        // check expiration
        if (idClaims.getExpirationTime() == null) {
          throw new AuthenticationServiceException(
              "Id Token does not have required expiration claim");
        } else {
          // it's not null, see if it's expired
          Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000));
          if (now.after(idClaims.getExpirationTime())) {
            throw new AuthenticationServiceException(
                "Id Token is expired: " + idClaims.getExpirationTime());
          }
        }

        // check not before
        if (idClaims.getNotBeforeTime() != null) {
          Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
          if (now.before(idClaims.getNotBeforeTime())) {
            throw new AuthenticationServiceException(
                "Id Token not valid untill: " + idClaims.getNotBeforeTime());
          }
        }

        // check issued at
        if (idClaims.getIssueTime() == null) {
          throw new AuthenticationServiceException(
              "Id Token does not have required issued-at claim");
        } else {
          // since it's not null, see if it was issued in the future
          Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
          if (now.before(idClaims.getIssueTime())) {
            throw new AuthenticationServiceException(
                "Id Token was issued in the future: " + idClaims.getIssueTime());
          }
        }

        // check audience
        if (idClaims.getAudience() == null) {
          throw new AuthenticationServiceException("Id token audience is null");
        } else if (!idClaims.getAudience().contains(clientConfig.getClientId())) {
          throw new AuthenticationServiceException(
              "Audience does not match, expected "
                  + clientConfig.getClientId()
                  + " got "
                  + idClaims.getAudience());
        }

        // compare the nonce to our stored claim
        String nonce = idClaims.getStringClaim("nonce");
        if (Strings.isNullOrEmpty(nonce)) {

          logger.error("ID token did not contain a nonce claim.");

          throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
        }

        String storedNonce = getStoredNonce(session);
        if (!nonce.equals(storedNonce)) {
          logger.error(
              "Possible replay attack detected! The comparison of the nonce in the returned "
                  + "ID Token to the session "
                  + NONCE_SESSION_VARIABLE
                  + " failed. Expected "
                  + storedNonce
                  + " got "
                  + nonce
                  + ".");

          throw new AuthenticationServiceException(
              "Possible replay attack detected! The comparison of the nonce in the returned "
                  + "ID Token to the session "
                  + NONCE_SESSION_VARIABLE
                  + " failed. Expected "
                  + storedNonce
                  + " got "
                  + nonce
                  + ".");
        }

        // construct an PendingOIDCAuthenticationToken and return a Authentication object w/the
        // userId and the idToken

        PendingOIDCAuthenticationToken token =
            new PendingOIDCAuthenticationToken(
                idClaims.getSubject(),
                idClaims.getIssuer(),
                serverConfig,
                idToken,
                accessTokenValue,
                refreshTokenValue);

        Authentication authentication = this.getAuthenticationManager().authenticate(token);

        return authentication;
      } catch (ParseException e) {
        throw new AuthenticationServiceException("Couldn't parse idToken: ", e);
      }
    }
  }