Ejemplo n.º 1
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String id = request.getParameter("id");
    String type = request.getParameter("type");
    String additions = request.getParameter("additions");
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    Form form = new Form();
    form.add("type", type);
    form.add("additions", additions);
    ClientResponse clientRsp =
        service
            .path("rest/orders")
            .path(id)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .put(ClientResponse.class, form);

    HttpSession session = request.getSession();

    if (clientRsp.getStatus() == 403) {
      String updateResponse = clientRsp.toString();
      session.setAttribute("updateResponse", updateResponse);
      response.sendRedirect("error.jsp?id=2");
    } else {
      String updateResponse = clientRsp.toString() + "\n" + clientRsp.getEntity(String.class);
      session.setAttribute("updateResponse", updateResponse);
      response.sendRedirect("orders.jsp");
    }
  }
Ejemplo n.º 2
0
  @Test
  public void meTokenPostForm() {

    Form form = new Form();
    form.add("grant_type", "password");
    form.add("username", "*****@*****.**");
    form.add("password", "test");

    JsonNode node =
        resource()
            .path("/management/me")
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .post(JsonNode.class);

    logNode(node);
    String token = node.get("access_token").getTextValue();

    assertNotNull(token);

    node =
        resource()
            .path("/management/me")
            .queryParam("access_token", token)
            .accept(MediaType.APPLICATION_JSON)
            .get(JsonNode.class);
    logNode(node);
  }
Ejemplo n.º 3
0
 public static void postForm(WebResource r, String id, String name) {
   Form form = new Form();
   form.add("id", id);
   form.add("name", name);
   ClientResponse response =
       r.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
   System.out.println(response.getEntity(String.class));
 }
  @Override
  public Subject register(String subject, SubjectConfig config) {
    Form form = new Form();
    for (Map.Entry<String, String> entry : RepositoryUtil.safeConfig(config).asMap().entrySet()) {
      form.putSingle(entry.getKey(), entry.getValue());
    }

    String regSubjectName =
        webResource
            .path(subject)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .put(String.class, form);

    return new RESTSubject(regSubjectName);
  }
Ejemplo n.º 5
0
  public static void main(String[] args) {

    Client c = Client.create();
    // This is for basic authentication
    // HTTPBasicAuthFilter auth= new HTTPBasicAuthFilter("richard", "testtest");
    // c.addFilter(auth);

    // This is for Multi Valued parms
    // MultivaluedMap queryParams = new MultivaluedMapImpl();
    // queryParams.add("j_username", "richard");
    // queryParams.add("j_password", "testtest");

    WebResource r = c.resource("https://localhost/jersey/autologin/login");
    Form form = new Form();
    form.add("j_username", "richard");
    form.add("j_password", "testtest");
    ClientResponse response =
        r.type(MediaType.APPLICATION_FORM_URLENCODED)
            .accept(MediaType.TEXT_HTML)
            .post(ClientResponse.class, form);
    System.out.println(response.getEntity(String.class));

    r = c.resource("https://localhost/jersey/sample/contacts");

    // add multi valued params
    // r = r.queryParams(queryParams);

    System.out.println("===== Get huangyim =====");
    getOneContact(r, "huangyim");

    System.out.println("===== Create foo =====");
    postForm(r, "foo", "bar");

    Address[] addrs = {new Address("Shanghai", "Ke Yuan Street")};
    Contact cnt = new Contact("guoqing", "Guo Qing", Arrays.asList(addrs));

    System.out.println("===== Create guoqing =====");
    putOneContact(r, cnt);

    System.out.println("===== All Contacts =====");
    getContacts(r);

    System.out.println("===== Delete foo =====");
    deleteOneContact(r, "foo");

    System.out.println("===== All Contacts =====");
    getContacts(r);
  }
Ejemplo n.º 6
0
  private void writeIndexes(Map<String, Object> indexFields, String messageKey)
      throws ActionProcessingException {
    //		try {
    //			ispnService.writeIndex(messageKey, indexFields);
    //		} catch (InfinispanException ex) {
    //			throw new ActionProcessingException("Exception happened while " +
    //			"writing index to Infinispan cache.", ex);
    //		}

    Form f = new Form();
    f.add("indexes", serializeMap(indexFields));
    Client c = Client.create();
    WebResource r = c.resource("http://localhost:8888/TuskUI/rest/indexer/add/" + messageKey);
    String indexResponse =
        r.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .accept(MediaType.TEXT_PLAIN)
            .post(String.class, f);
    LOG.info(
        "Done writing message indexes for key " + messageKey + "; response was " + indexResponse);
  }
  public static List<PatientSearchResult> getTextSearch(String textValue, String userToken) {

    Form form = new Form();
    form.add("textValue", textValue);

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create();
    WebResource resource =
        client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getTextSearch");
    ClientResponse response =
        resource
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .header("Authorization", "Bearer " + userToken)
            .post(ClientResponse.class, form);
    // check response status code
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    // display response
    String output = response.getEntity(String.class);
    List<PatientTextSearchResult> myObjects;
    try {
      // Object json = mapper.readValue(output, Object.class);
      //  String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
      // logger.info("Returned JSON\n"+indented);
      myObjects =
          mapper.readValue(output, new TypeReference<List<PatientTextSearchResultImpl>>() {});
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    List<PatientSearchResult> returnValue = new ArrayList<PatientSearchResult>();
    for (PatientTextSearchResult result : myObjects) {
      returnValue.add(result);
    }
    return returnValue;
  }
  public static List<ImageDTO> getImageDrillDown(List<Integer> criteria, String userToken) {

    Form form = new Form();
    int i = 0;
    // List of selected series
    for (Integer dcriteria : criteria) {
      form.add("list", dcriteria.toString());
    }

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create();
    WebResource resource =
        client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getImageDrillDown");
    ClientResponse response =
        resource
            .accept(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + userToken)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .post(ClientResponse.class, form);
    // check response status code
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    // display response
    String output = response.getEntity(String.class);
    List<ImageDTO> myObjects;
    try {
      //	Object json = mapper.readValue(output, Object.class);
      //    String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
      //    logger.info("Returned JSON\n"+indented);
      myObjects = mapper.readValue(output, new TypeReference<List<ImageDTO>>() {});
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return myObjects;
  }
Ejemplo n.º 9
0
  /*
   * This test obtains a valid token from VDC1.
   * - It will try to access the tenant resource of VDC1 by going through the formlogin resource with service= and the token
   * as form parameter.  This is not really a real use case (one would normally pass credentials to formlogin of its own VDC)
   * but it's to make sure there are no ill effects if one did that.
   * - More importantly, try the same thing but against VDC2.  So access VDC2's tenant resource through service= redirect
   * on the formlogin with no credentials, and the token from VDC1.  This is to exercise the SSO functionality from the UI
   * point of view.
   */
  @Test
  public void SSOformLogin() throws Exception {
    BalancedWebResource rAdmin = createHttpsClient(ZONEADMIN, AD_PASS_WORD, baseUrls, true);
    _savedTokens.remove(ZONEADMIN);
    ClientResponse resp = rAdmin.path("/tenant").get(ClientResponse.class);
    String vdc1Token = (String) _savedTokens.get(ZONEADMIN);
    _savedTokens.remove(ZONEADMIN);

    Form formLogin = new Form();
    formLogin.add("auth-token", vdc1Token);
    BalancedWebResource rAnonVDC1 = createHttpsClient("", "", baseUrls, true);
    resp =
        rAnonVDC1
            .path("/formlogin")
            .queryParam("service", baseUrls.get(0) + "/tenant")
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .post(ClientResponse.class, formLogin);
    Assert.assertEquals(200, resp.getStatus());

    _savedTokens.remove(ZONEADMIN);

    _lastUsedAuthTokenCookie = null;

    BalancedWebResource rAnonVDC2 =
        createHttpsClient("", "", Collections.singletonList(remoteVDCVIP), true);
    resp =
        rAnonVDC2
            .path("/formlogin")
            .queryParam("service", remoteVDCVIP + "/tenant")
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .post(ClientResponse.class, formLogin);
    Assert.assertEquals(200, resp.getStatus());
    // check that vdc2 sent us a new cookie and its value is equal to the vdc1 token
    Assert.assertNotNull(_lastUsedAuthTokenCookie);

    Assert.assertEquals(vdc1Token, _lastUsedAuthTokenCookie);
  }
  public static DefaultOAuth2AccessToken getToken(String userName, String password) {

    Form form = new Form();
    form.add("username", userName);
    form.add("password", password);
    form.add("client_id", "nbiaRestAPIClient");
    form.add("client_secret", "ItsBetweenUAndMe");
    form.add("grant_type", "password");

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create();
    WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/oauth/token");
    ClientResponse response =
        resource
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .post(ClientResponse.class, form);
    // check response status code
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    // display response
    String output = response.getEntity(String.class);
    output = "[" + output + "]";
    List<DefaultOAuth2AccessToken> myObjects;
    try {
      myObjects = mapper.readValue(output, new TypeReference<List<DefaultOAuth2AccessToken>>() {});
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return myObjects.get(0);
  }
  // TODO fix failing test
  public void test1() {
    DefaultResourceConfig drc = new DefaultResourceConfig(StringResource.class);
    initParams.put(
        ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES,
        "com.sun.jersey.server.hypermedia.filter.HypermediaFilterFactory");
    drc.setPropertiesAndFeatures(initParams);
    startServer(drc);

    Client c = Client.create();
    ViewResource r = c.viewResource(getUri().path("strings").path("1").build());
    StringController sc = r.get(StringController.class);

    // Test static annotation @FormParam
    Form f = new Form();
    f.add("p3", "boo");
    assert (sc.action1("foo", "bar").equals("foobar"));
    assert (sc.action2("foo", "bar", f).equals("foobar"));

    // Test @Name mapped dynamically using WADL
    f = new Form();
    f.add("p3", "boo");
    assert (sc.action11("foo", "bar").equals("foobar"));
    assert (sc.action21("foo", "bar", f).equals("foobar"));
  }
Ejemplo n.º 12
0
  // Dans cette fonction nous allons récupérer des identifiants d'utilisateurs
  @Test
  public void testGetUsers() throws Exception {
    Form f = new Form();
    WebResource webResource;
    ClientResponse result;
    System.out.println("****************** Recupereration des utilisateurs ! ******************");

    // tente de récupérer un utilisateur sans être connecté: échec attendu
    webResource = client.resource(new URL(this.baseUrl + "/users/getuserid/1").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.USER_OFFLINE, result.getStatus());
    System.out.println(
        "Un utilisateur non connecte tente, sans succes, de recuperer les informations de l'utilisateur 1 par id");
    result.close();

    webResource =
        client.resource(new URL(this.baseUrl + "/users/getuseremail/[email protected]").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.USER_OFFLINE, result.getStatus());
    System.out.println(
        "Un utilisateur non connecte tente, sans succes, de recuperer les informations de l'utilisateur 1 par email");
    result.close();

    webResource = client.resource(new URL(this.baseUrl + "/users/search/jul").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.USER_OFFLINE, result.getStatus());
    System.out.println(
        "Un utilisateur non connecte tente, sans succes, de rechercher des utilisateurs par nom");
    result.close();

    // Connexion de l'utilisateur 1: succès attendu
    f.add("email", "*****@*****.**");
    f.add("password", "password");
    webResource = client.resource(new URL(this.baseUrl + "/connection").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, f);
    Assert.assertEquals(Status.OK, result.getStatus());
    System.out.println("L'utilisateur 1 se connecte");
    result.close();

    // tente de récupérer un utilisateur inexistant par id: échec attendu
    webResource = client.resource(new URL(this.baseUrl + "/users/getuserid/132324").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.USER_NO_ACCOUNT, result.getStatus());
    System.out.println(
        "L'utilisateur 1 n'arrive pas a recuperer les informations d'un utilisateur inexistant");
    result.close();

    // récupère l'utilisateur ayant l'id 1 : succès attendu
    webResource = client.resource(new URL(this.baseUrl + "/users/getuserid/1").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.OK, result.getStatus());
    System.out.println(
        "L'utilisateur 1 recupere les informations de l'utilisateur 1 par identifiant technique");
    result.close();

    // tente de récupérer un utilisateur inexistant par email: échec attendu
    webResource =
        client.resource(
            new URL(this.baseUrl + "/users/getuseremail/[email protected]").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.USER_NO_ACCOUNT, result.getStatus());
    System.out.println(
        "L'utilisateur 1 tente de recuperer, sans succes, les informations d'un utilisateur inexistant par email");
    result.close();

    // récupère l'utilisateur 5 ayant l'email [email protected] : succès attendu
    webResource =
        client.resource(new URL(this.baseUrl + "/users/getuseremail/[email protected]").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.OK, result.getStatus());
    System.out.println("L'utilisateur 1 recupere les informations de l'utilisateur 5 par email");
    result.close();

    // récupère la liste des utilisateurs dont une partie du nom est 'n': succès attendu
    webResource = client.resource(new URL(this.baseUrl + "/users/search/n").toURI());
    result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    Assert.assertEquals(Status.OK, result.getStatus());
    List<LinkedHashMap<String, ?>> listUser = result.getEntity(List.class);
    String res = "L'utilisateur 1 recherche les utilisateurs possedants 'n' dans leur nom: ";
    for (LinkedHashMap<String, ?> u : listUser) {
      res += u.get("email") + "  ";
    }
    System.out.println(res);
    result.close();
  }
  /**
   * IHTSDO authenticate.
   *
   * @param username the username
   * @param password the password
   * @return the string
   * @throws Exception the exception
   */
  @SuppressWarnings("unchecked")
  private String ihtsdoAuthenticate(String username, String password) throws Exception {

    String ihtsdoSecurityUrl = config.getProperty("ihtsdo.security.url");

    // set up request to be posted to ihtsdo security service
    Form form = new Form();
    form.add("username", username);
    form.add("password", password);
    form.add("queryName", "getUserByNameAuth");

    Client client = Client.create();
    WebResource resource = client.resource(ihtsdoSecurityUrl);

    resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE);

    ClientResponse response = resource.post(ClientResponse.class, form);

    String resultString = "";
    if (response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
      resultString = response.getEntity(String.class);
    } else {
      // TODO Differentiate error messages with NO RESPONSE and
      // Authentication Failed (Check text)
      Logger.getLogger(this.getClass()).info("ERROR! " + response.getStatus());
      resultString = response.getEntity(String.class);
      Logger.getLogger(this.getClass()).info(resultString);
      throw new LocalException("Incorrect user name or password.");
    }

    /*
     * Synchronize the information sent back from ITHSDO with the MapUser
     * object. Add a new map user if there isn't one matching the username If
     * there is, load and update that map user and save the changes
     */
    String ihtsdoUserName = "";
    String ihtsdoEmail = "";
    String ihtsdoGivenName = "";
    String ihtsdoSurname = "";

    // converting json to Map
    byte[] mapData = resultString.getBytes();
    Map<String, HashMap<String, String>> jsonMap = new HashMap<>();

    // parse username from json object
    ObjectMapper objectMapper = new ObjectMapper();
    jsonMap = objectMapper.readValue(mapData, HashMap.class);
    for (Entry<String, HashMap<String, String>> entrySet : jsonMap.entrySet()) {
      if (entrySet.getKey().equals("user")) {
        HashMap<String, String> innerMap = entrySet.getValue();
        for (Entry<String, String> innerEntrySet : innerMap.entrySet()) {
          if (innerEntrySet.getKey().equals("name")) {
            ihtsdoUserName = innerEntrySet.getValue();
          } else if (innerEntrySet.getKey().equals("email")) {
            ihtsdoEmail = innerEntrySet.getValue();
          } else if (innerEntrySet.getKey().equals("givenName")) {
            ihtsdoGivenName = innerEntrySet.getValue();
          } else if (innerEntrySet.getKey().equals("surname")) {
            ihtsdoSurname = innerEntrySet.getValue();
          }
        }
      }
    }
    // check if ihtsdo user matches one of our MapUsers
    MappingService mappingService = new MappingServiceJpa();
    MapUserList userList = mappingService.getMapUsers();
    MapUser userFound = null;
    for (MapUser user : userList.getMapUsers()) {
      if (user.getUserName().equals(ihtsdoUserName)) {
        userFound = user;
        break;
      }
    }
    // if MapUser was found, update to match ihtsdo settings
    if (userFound != null) {
      userFound.setEmail(ihtsdoEmail);
      userFound.setName(ihtsdoGivenName + " " + ihtsdoSurname);
      userFound.setUserName(ihtsdoUserName);
      mappingService.updateMapUser(userFound);
      // if MapUser not found, create one for our use
    } else {
      MapUser newMapUser = new MapUserJpa();
      newMapUser.setName(ihtsdoGivenName + " " + ihtsdoSurname);
      newMapUser.setUserName(ihtsdoUserName);
      newMapUser.setEmail(ihtsdoEmail);
      newMapUser.setApplicationRole(MapUserRole.VIEWER);
      mappingService.addMapUser(newMapUser);
    }
    mappingService.close();

    // Generate application-managed token
    String token = UUID.randomUUID().toString();
    tokenUsernameMap.put(token, ihtsdoUserName);
    tokenLoginMap.put(token, new Date());

    Logger.getLogger(this.getClass()).info("User = " + resultString);

    return token;
  }