private static WebResource.Builder getBuilder(
      String url, String authorization, Map<String, String> key, Boolean overwrite) {
    Client client = Client.create();
    WebResource wr = client.resource(url);

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();

    if (key != null && !key.isEmpty()) {
      for (String k : key.keySet()) {
        queryParams.add(k, key.get(k));
      }
    }

    if (overwrite != null && overwrite) {
      queryParams.add(CLOUDHUB_OVERRITE_REST_PARAMETER, overwrite.toString());
    }

    if (queryParams.isEmpty()) {
      return wr.header(HTTP_AUTH_HEADER_NAME, authorization).type(MediaType.APPLICATION_JSON);
    } else {
      return wr.queryParams(queryParams)
          .header(HTTP_AUTH_HEADER_NAME, authorization)
          .type(MediaType.APPLICATION_JSON);
    }
  }
Beispiel #2
0
 protected JSONArray invoke(WebResource resource) {
   return (JSONArray)
       ((JSONObject)
               JSONValue.parse(
                   resource.header("Authorization", "Basic " + base64Hash).get(String.class)))
           .get("list");
 }
 @Override
 public String getStringResponse(
     String root, String path, Mappable params, Map<String, String> headers) {
   try {
     int idx = path.indexOf(configuration.getVersion());
     if (idx > -1) path = path.substring(idx + configuration.getVersion().length());
     MultivaluedMap<String, String> queryParams =
         params == null ? new MultivaluedMapImpl() : params.toMap();
     WebResource resource =
         getClient()
             .resource(root)
             .path(configuration.getVersion())
             .path(path)
             .queryParams(queryParams);
     WebResource.Builder builder = resource.getRequestBuilder();
     if (headers != null) {
       for (String key : headers.keySet()) {
         builder = resource.header(key, headers.get(key));
       }
     }
     String response =
         builder
             .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XHTML_XML)
             .get(String.class);
     logger.fine(response);
     return response;
   } catch (BaseSpaceException bs) {
     throw bs;
   } catch (Throwable t) {
     throw new RuntimeException(t);
   }
 }
Beispiel #4
0
  public Resource getResource(Long id, boolean full) {
    WebResource resource = getBaseWebResource("resources", "resource", id);
    if (full) resource = resource.queryParam("full", Boolean.toString(full));

    return resource
        .header("Content-Type", MediaType.TEXT_XML)
        .accept(MediaType.TEXT_XML)
        .get(Resource.class);
  }
 public UserGroupList getUserGroups(Integer page, Integer entries, boolean all) {
   WebResource wr = getBaseWebResource("usergroups");
   wr = wr.queryParam("page", page.toString());
   wr = wr.queryParam("entries", entries.toString());
   wr = wr.queryParam("all", "" + all);
   return wr.header("Content-Type", MediaType.TEXT_XML)
       .accept(MediaType.TEXT_XML)
       .get(UserGroupList.class);
 }
 public ShortResourceList updateSecurityRules(
     ShortResourceList resourcesToSet, Long groupId, boolean canRead, boolean canWrite) {
   WebResource wr =
       getBaseWebResource("usergroups", "update_security_rules", groupId, canRead, canWrite);
   ShortResourceList updatedResources =
       wr.header("Content-Type", MediaType.TEXT_XML)
           .accept(MediaType.TEXT_XML)
           .put(ShortResourceList.class, resourcesToSet);
   return updatedResources;
 }
Beispiel #7
0
  public ExtGroupList searchUserGroup(Integer start, Integer limit, String nameLike, boolean all) {
    WebResource wr = getBaseWebResource("extjs", "search", "groups", nameLike);

    wr =
        wr.queryParam("start", start.toString())
            .queryParam("limit", limit.toString())
            .queryParam("all", Boolean.toString(all));

    return wr.header("Content-Type", MediaType.TEXT_XML)
        .accept(MediaType.TEXT_XML)
        .get(ExtGroupList.class);
  }
  public void testPost() {
    startServer(HttpMethodResource.class);

    DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
    config.getClasses().add(HeaderWriter.class);
    ApacheHttpClient c = ApacheHttpClient.create(config);

    WebResource r = c.resource(getUri().path("test").build());

    ClientResponse cr = r.header("X-CLIENT", "client").post(ClientResponse.class, "POST");
    assertEquals(200, cr.getStatus());
    assertTrue(cr.hasEntity());
    cr.close();
  }
Beispiel #9
0
 @SuppressWarnings("unused")
 private static void invokeDeleteMethod(String auth, String url)
     throws AuthenticationException, ClientHandlerException {
   Client client = Client.create();
   WebResource webResource = client.resource(url);
   ClientResponse response =
       webResource
           .header("Authorization", "Basic " + auth)
           .type("application/json")
           .accept("application/json")
           .delete(ClientResponse.class);
   int statusCode = response.getStatus();
   if (statusCode == 401) {
     throw new AuthenticationException("Invalid Username or Password");
   }
 }
Beispiel #10
0
 private static String invokePostMethod(String auth, String url, String data)
     throws AuthenticationException, ClientHandlerException {
   Client client = Client.create();
   WebResource webResource = client.resource(url);
   ClientResponse response =
       webResource
           .header("Authorization", "Basic " + auth)
           .type("application/json")
           .accept("application/json")
           .post(ClientResponse.class, data);
   int statusCode = response.getStatus();
   if (statusCode == 401) {
     throw new AuthenticationException("Invalid Username or Password");
   }
   return response.getEntity(String.class);
 }
  public void testPostChunked() {
    ResourceConfig rc = new DefaultResourceConfig(HttpMethodResource.class);
    rc.getProperties()
        .put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, LoggingFilter.class.getName());
    startServer(rc);

    DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
    config.getClasses().add(HeaderWriter.class);
    config.getProperties().put(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE, 1024);
    ApacheHttpClient c = ApacheHttpClient.create(config);

    WebResource r = c.resource(getUri().path("test").build());

    ClientResponse cr = r.header("X-CLIENT", "client").post(ClientResponse.class, "POST");
    assertEquals(200, cr.getStatus());
    assertTrue(cr.hasEntity());
    cr.close();
  }
Beispiel #12
0
  public ResourceList searchResources(
      SearchFilter searchFilter,
      Integer page,
      Integer entries,
      Boolean includeAttributes,
      Boolean includeData) {
    WebResource wb = getBaseWebResource("resources", "search", "list");

    wb = addQParam(wb, "page", page);
    wb = addQParam(wb, "entries", entries);

    wb = addQParam(wb, "includeAttributes", includeAttributes);
    wb = addQParam(wb, "includeData", includeData);

    return wb.header("Content-Type", MediaType.TEXT_XML)
        .accept(MediaType.TEXT_XML)
        .post(ResourceList.class, searchFilter);
  }
 public ClientResponse updateProject(ProjectInfo info, User userInfo) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug("Entering Method ServiceManagerImpl.updateProject(ProjectInfo info)");
   }
   Client client = ClientHelper.createClient();
   FrameworkConfiguration configuration = PhrescoFrameworkFactory.getFrameworkConfig();
   WebResource resource =
       client.resource(configuration.getServerPath() + FrameworkConstants.REST_APPS_UPDATE_PATH);
   resource.accept(MediaType.APPLICATION_OCTET_STREAM);
   if (debugEnabled) {
     S_LOGGER.debug("updateProject() ProjectName = " + info.getName());
   }
   ClientResponse response =
       resource
           .header(Constants.AUTH_TOKEN, userInfo.getToken())
           .type(MediaType.APPLICATION_JSON)
           .post(ClientResponse.class, info);
   return response;
 }
Beispiel #14
0
 protected ClientResponse delete(WebResource resource) {
   return resource
       .header("Authorization", "Basic " + base64Hash)
       .type(MediaType.APPLICATION_JSON_TYPE)
       .delete(ClientResponse.class);
 }
Beispiel #15
0
 protected ClientResponse post(WebResource resource, String arg) {
   return resource
       .header("Authorization", "Basic " + base64Hash)
       .type(MediaType.APPLICATION_JSON_TYPE)
       .post(ClientResponse.class, arg);
 }
 private String getString(String operation) {
   WebResource path = client.path("/").queryParam(operation, "");
   Builder req = path.header("Accept-Encoding", "gzip;q=0");
   return req.get(String.class);
 }
  @Override
  public void doRegistration(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY, null);

    UserData result = new UserData();
    if (request == null) {
      VaadinSession.getCurrent().setAttribute("registration_pending", getLoginIdentifier());
      Page.getCurrent()
          .setLocation(
              "https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                  + clientId
                  + "&response_type=code&scope=write&redirect_uri="
                  + UIHelper.getWebAppUrl().toString());
    } else {
      // delete auth_pending attribute as we'll finish now or never
      VaadinSession.getCurrent().setAttribute("registration_pending", null);
      // obtain remaining information and do redirect
      // do actual login
      LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
      String code = request.getParameter("code");

      MultivaluedMap formData = new MultivaluedMapImpl();
      formData.putSingle("client_id", clientId);
      formData.putSingle("client_secret", clientSecret);
      formData.putSingle("grant_type", "authorization_code");
      formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
      formData.putSingle("code", code);

      ClientConfig config = new DefaultClientConfig();
      IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
      mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
      try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] {TRUST_MANAGER}, new SecureRandom());
        config
            .getProperties()
            .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(VERIFIER, ctx));
        Client client = Client.create(config);
        WebResource webResource =
            client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
        webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

        LOGGER.debug("Obtaining access token.");
        ClientResponse response =
            webResource
                .header("Content-Type", "application/x-www-form-urlencoded")
                .accept(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, formData);

        if (response.getStatus() == 200) {
          String responseData = response.getEntity(String.class);
          JSONObject responseObject = new JSONObject(responseData);
          String access_token = responseObject.getString("access_token");
          webResource =
              client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");

          LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
          response =
              webResource
                  .header("Content-Type", "application/x-www-form-urlencoded")
                  .accept(MediaType.APPLICATION_JSON)
                  .header("Authorization", "Bearer " + access_token)
                  .get(ClientResponse.class);

          if (response.getStatus() == 200) {
            JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
            try {
              String userId = userInfoResponse.getString("sub");
              List<UserData> existingUsers =
                  mdm.findResultList(
                      "Select u FROM UserData u WHERE u.distinguishedName=?1",
                      new Object[] {userId},
                      UserData.class);
              if (!existingUsers.isEmpty()) {
                // user for B2Access subject already exists...unable to continue
                throw new UnauthorizedAccessAttemptException(
                    "There is already a user registered for the obtained B2Access id '"
                        + userId
                        + "'.");
              }
              result.setDistinguishedName(userId);
            } catch (JSONException ex) {
              // failed, not enough information to proceed!
            }
          } else {
            // failed, not enough information to proceed!
          }
        } else {
          // failed, not enough information to proceed!
        }
      } catch (NoSuchAlgorithmException | KeyManagementException | JSONException ex) {
        LOGGER.error("Failed to collect information from B2Access service.", ex);
        throw new UnauthorizedAccessAttemptException(
            "Failed to collect information from B2Access service.", ex);
      } finally {
        mdm.close();
      }
      setup(AUTH_MODE.REGISTRATION, result);
    }
  }
 private void putXML(String operation, String data) {
   WebResource path = client.path("/").queryParam(operation, "");
   Builder req = path.header("Accept-Encoding", "gzip;q=0");
   req.header("Content-Type", "text/xml").put(data);
 }
Beispiel #19
0
 public SecurityRuleList getSecurityRules(Long resourceId) {
   WebResource wr = getBaseWebResource("resources", "resource", resourceId, "permissions");
   return wr.header("Content-Type", MediaType.TEXT_XML)
       .accept(MediaType.TEXT_XML)
       .get(SecurityRuleList.class);
 }
 public void testHeader() throws Exception {
   WebResource h1 = client.path("/").queryParam("either", "");
   assertEquals("hello h1", h1.header("h1", "h1").get(String.class));
 }
  @Override
  public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret =
        DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY, null);

    if (request == null) {
      // set auth_pending attribute in order to be able to finish authentication later
      VaadinSession.getCurrent().setAttribute("auth_pending", getLoginIdentifier());
      Page.getCurrent()
          .setLocation(
              "https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                  + clientId
                  + "&response_type=code&scope=/authenticate&redirect_uri="
                  + UIHelper.getWebAppUrl().toString());
    } else {
      // delete auth_pending attribute as we'll finish now or never
      VaadinSession.getCurrent().setAttribute("auth_pending", null);
      // obtain remaining information and do redirect
      // do actual login
      LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
      String code = request.getParameter("code");

      MultivaluedMap formData = new MultivaluedMapImpl();
      formData.putSingle("client_id", clientId);
      formData.putSingle("client_secret", clientSecret);
      formData.putSingle("grant_type", "authorization_code");
      formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
      formData.putSingle("code", code);

      ClientConfig config = new DefaultClientConfig();
      IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
      mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
      try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] {TRUST_MANAGER}, new SecureRandom());

        config
            .getProperties()
            .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(VERIFIER, ctx));
        Client client = Client.create(config);
        WebResource webResource =
            client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
        webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

        LOGGER.debug("Obtaining access token.");
        ClientResponse response =
            webResource
                .header("Content-Type", "application/x-www-form-urlencoded")
                .accept(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, formData);

        if (response.getStatus() == 200) {
          LOGGER.debug("Response status is HTTP 200. Parsing JSON response.");
          String responseData = response.getEntity(String.class);
          JSONObject responseObject = new JSONObject(responseData);
          String access_token = responseObject.getString("access_token");
          webResource =
              client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");
          LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
          response =
              webResource
                  .header("Content-Type", "application/x-www-form-urlencoded")
                  .accept(MediaType.APPLICATION_JSON)
                  .header("Authorization", "Bearer " + access_token)
                  .get(ClientResponse.class);

          if (response.getStatus() == 200) {
            JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
            String userId = userInfoResponse.getString("sub");
            UserData result =
                mdm.findSingleResult(
                    "Select u FROM UserData u WHERE u.distinguishedName=?1",
                    new Object[] {userId},
                    UserData.class);
            if (result != null) {
              LOGGER.debug(
                  "User with distinguished name {} found. Logging in and redirecting user.",
                  userId);
              UIHelper.login(
                  new UserId(result.getDistinguishedName()), new GroupId(Constants.USERS_GROUP_ID));
            } else {
              LOGGER.warn("No user found for ORCiD {}. Login denied.", userId);
              throw new UnauthorizedAccessAttemptException(
                  "No user found for ORCiD '" + userId + "'.");
            }
          } else {
            // failed, not enough information to proceed!
          }
        } else {
          throw new HttpException(
              "Failed to obtain access token from ORCiD service. Status is "
                  + response.getStatus()
                  + ", response data is: "
                  + response.getEntity(String.class));
        }

        // {"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
        // https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
      } catch (NoSuchAlgorithmException | KeyManagementException | HttpException ex) {
        LOGGER.error("Failed to access B2Access service.", ex);
        throw new UnauthorizedAccessAttemptException("Failed to login via B2Access.", ex);
      } finally {
        mdm.close();
      }

      String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
      if (fromPage != null) {
        VaadinSession.getCurrent().setAttribute("from", null);
        Page.getCurrent().setLocation(fromPage);
      } else {
        Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
      }
    }
  }