/**
  * Extracts the XML string associated with an uploaded multipath file item.
  *
  * @return the XML string (null if none)
  * @throws UnsupportedEncodingException (should never be thrown)
  */
 private String extractItemXml(FileItem item) throws UnsupportedEncodingException {
   String xml = null;
   if (item != null) {
     xml = Val.chkStr(Val.removeBOM(item.getString("UTF-8")));
   }
   return xml;
 }
 /**
  * Add attribute to ldap entry.
  *
  * @param request HTTP request.
  * @param response HTTP response.
  * @param context request context
  * @throws IdentityException if a system error occurs preventing the action
  * @throws IOException if error writing to the buffer
  * @throws NamingException if an LDAP naming exception occurs
  * @throws SQLException
  * @throws CredentialPolicyException
  */
 private void executeModifyUserAttribute(
     HttpServletRequest request,
     HttpServletResponse response,
     RequestContext context,
     boolean isAddAttributeRequest)
     throws IdentityException, IOException, NamingException, SQLException,
         CredentialPolicyException {
   String mimeType = "application/json";
   String filter = Val.chkStr(request.getParameter("q"));
   String attributeName = Val.chkStr(request.getParameter("an"));
   String attributeValue = Val.chkStr(request.getParameter("av"));
   if (filter.length() == 0) {
     response.getWriter().write("{ \"response\" : \"noResults\" }");
     return;
   }
   IdentityAdapter idAdapter = context.newIdentityAdapter();
   Users users = idAdapter.readUsers(filter, null);
   for (User u : users.values()) {
     if (isAddAttributeRequest) {
       try {
         idAdapter.addAttribute(u.getDistinguishedName(), attributeName, attributeValue);
       } catch (AttributeInUseException aiue) {
         // TODO : do nothing if attribute exists ? or overwrite ?
       }
     } else {
       idAdapter.removeAttribute(u.getDistinguishedName(), attributeName, attributeValue);
     }
   }
   writeCharacterResponse(
       response,
       "{ \"response\" : \"User attribute modification was successful.\" }",
       "UTF-8",
       mimeType + ";charset=UTF-8");
 }
  /**
   * Writes abstract section.
   *
   * @param record record
   */
  private void writeAbstract(SearchResultRecord record) {
    String sAbstract = Val.chkStr(record.getAbstract());

    if (sAbstract.length() > 0) {
      sAbstract =
          !getClipText()
              ? sAbstract
              : sAbstract.length() > CLIP_TEXT_LENGTH
                  ? sAbstract.substring(0, CLIP_TEXT_LENGTH) + "..."
                  : sAbstract;

      String divStyle = "overflow: auto;";
      _writer.println("<div class=\"" + ABSTRACT_STYLE_CLASS + "\" style=\"" + divStyle + "\" >");

      String url = Val.chkStr(record.getResourceLinks().getThumbnail().getUrl());
      if (url.length() > 0) {
        url = Val.escapeXml(url);
        String imgStyle =
            "float:right; margin-left:0.5em; width:64px; height:64px; border:1px solid #000000;";
        // imgStyle = "border:1px solid #000000;";
        _writer.println(
            "<img class=\""
                + THUMBNAIL_STYLE_CLASS
                + "\" src=\""
                + url
                + "\" style=\""
                + imgStyle
                + "\"/>");
      }
      _writer.println(Val.escapeXmlForBrowser(sAbstract));
      _writer.println("</div>");
    }
  }
Esempio n. 4
0
 /**
  * Provides XML snippet of the record.
  *
  * @return XML snippet of the record
  */
 public String toXmlSnippet() {
   StringBuilder sb = new StringBuilder();
   sb.append("<record>\n");
   sb.append("<sourceUri>" + Val.escapeXml(sourceUri) + "</sourceUri>\n");
   if (!validated) {
     sb.append("<validate>\n");
     sb.append("<status>failed</status>\n");
     for (String error : errors) {
       sb.append("<error>" + Val.escapeXml(error) + "</error>\n");
     }
     sb.append("</validate>\n");
   } else {
     sb.append("<validate><status>ok</status></validate>\n");
     if (!published) {
       sb.append("<publish>\n");
       sb.append("<status>failed</status>\n");
       for (String error : errors) {
         sb.append("<error>" + Val.escapeXml(error) + "</error>\n");
       }
       sb.append("</publish>\n");
     } else {
       sb.append("<publish><status>ok</status></publish>\n");
     }
   }
   sb.append("</record>\n");
   return sb.toString();
 }
  /**
   * Executes a remove member action.
   *
   * @param request HTTP request.
   * @param response HTTP response.
   * @param context request context
   * @throws Exception if an exception occurs
   */
  protected void executeRemoveMember(
      HttpServletRequest request, HttpServletResponse response, RequestContext context)
      throws Exception {
    try {
      String[] parts = request.getRequestURI().toString().split("/");
      String member = Val.chkStr(request.getParameter("member"));
      String attempt = Val.chkStr(request.getParameter("attempt"));
      IdentityAdapter idAdapter = context.newIdentityAdapter();
      User user = new User();
      user.setDistinguishedName(member);
      idAdapter.readUserProfile(user);
      if (parts.length > 0) {
        String groupIdentifier = URLDecoder.decode(parts[5].trim(), "UTF-8");
        if (!groupIdentifier.endsWith(groupDIT)) {
          IdentityConfiguration idConfig = context.getIdentityConfiguration();
          Roles configuredRoles = idConfig.getConfiguredRoles();
          Role roleRegistered = configuredRoles.get(groupIdentifier);
          groupIdentifier = roleRegistered.getDistinguishedName();
        }
        boolean isSelf = checkSelf(context, member);
        if ((isSelf && attempt.equals("2")) || !isSelf) {

          boolean checkGroupConfigured = true;
          if (checkIfAllowConfigured(context)) {
            checkGroupConfigured = checkIfConfigured(context, groupIdentifier);
          }
          boolean isAllowedToManage = true;
          isAllowedToManage = checkIfAllowedToManage(context, groupIdentifier);
          if (checkGroupConfigured) {
            if (isAllowedToManage) {
              idAdapter.removeUserFromGroup(user, groupIdentifier);
              response
                  .getWriter()
                  .write(msgBroker.retrieveMessage("catalog.identity.removeRole.success"));
            } else {
              response.sendError(
                  HttpServletResponse.SC_BAD_REQUEST,
                  "{ \"error\":\""
                      + groupIdentifier
                      + " is not allowed to be managed in geoportal. \"}");
              return;
            }
          } else {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "{ \"error\":\"" + groupIdentifier + " is not configured in geoportal. \"}");
            return;
          }

        } else {
          response.getWriter().write("prompt");
        }
      }
    } finally {
    }
  }
 /**
  * Writes link.
  *
  * @param url link URL
  * @param text link text
  */
 private void writeLink(String url, String text) {
   url = Val.chkStr(url);
   text = Val.chkStr(text);
   if (url.length() > 0) {
     _writer.print("<A HREF=\"");
     _writer.print(Val.escapeXmlForBrowser(url));
     _writer.print("\" target=\"" + _target.toHtmlValue() + "\">");
     _writer.print(Val.escapeXmlForBrowser(text));
     _writer.println("</A>");
   }
 }
Esempio n. 7
0
 /**
  * Constructs the set of supported values from a delimited string.
  *
  * @param tokens the delimited string to tokenize
  * @param delimiter the delimiter
  */
 public SupportedValues(String tokens, String delimiter) {
   tokens = Val.chkStr(tokens);
   if (delimiter == null) {
     this.supported.put(tokens, tokens);
   } else {
     StringTokenizer st = new StringTokenizer(tokens, delimiter);
     while (st.hasMoreElements()) {
       String token = Val.chkStr((String) st.nextElement());
       this.supported.put(token, token);
     }
   }
 }
  /**
   * Parses protocol.
   *
   * @param xmlString protocol as XML string
   * @return protocol
   * @throws ProtocolException if error parsing protocol
   */
  public Protocol parseProtocol(String xmlString) {
    try {
      Document doc = DomUtil.makeDomFromString(xmlString, false);

      String protocolName = "";
      long flags = 0;
      List<String> vDest = null;
      StringAttributeMap properties = new StringAttributeMap();
      NodeList protocolNL = doc.getElementsByTagName("protocol");

      if (protocolNL.getLength() >= 1) {
        Node protocolN = protocolNL.item(0);

        NamedNodeMap attributes = protocolN.getAttributes();

        Node protocolTypeN = attributes.getNamedItem("type");
        protocolName = Val.chkStr(protocolTypeN != null ? protocolTypeN.getNodeValue() : "");

        Node flagsN = attributes.getNamedItem("flags");
        flags = flagsN != null ? Val.chkLong(Val.chkStr(flagsN.getNodeValue()), 0) : 0;

        Node destinationsN = attributes.getNamedItem("destinations");
        String sDest = destinationsN != null ? Val.chkStr(destinationsN.getNodeValue()) : null;
        vDest = sDest != null ? Arrays.asList(sDest.split(",")) : null;

        NodeList propertiesNL = protocolN.getChildNodes();
        for (int i = 0; i < propertiesNL.getLength(); i++) {
          Node property = propertiesNL.item(i);
          String propertyName = property.getNodeName();
          String propertyValue = property.getTextContent();
          properties.set(propertyName, propertyValue);
        }
      }

      ProtocolFactory protocolFactory = get(protocolName);
      if (protocolFactory == null) {
        throw new IllegalArgumentException("Unsupported protocol: " + protocolName);
      }

      Protocol protocol = protocolFactory.newProtocol();
      protocol.setFlags(flags);
      protocol.applyAttributeMap(properties);
      ProtocolInvoker.setDestinations(protocol, vDest);

      return protocol;
    } catch (ParserConfigurationException ex) {
      throw new IllegalArgumentException("Error parsing protocol.", ex);
    } catch (SAXException ex) {
      throw new IllegalArgumentException("Error parsing protocol.", ex);
    } catch (IOException ex) {
      throw new IllegalArgumentException("Error parsing protocol.", ex);
    }
  }
Esempio n. 9
0
 /**
  * Builds a full distinguished name based upon a relative DN and base DN.
  *
  * @param objectDN the relative object DN
  * @param baseDN the base DN (for a search)
  * @return the full DN
  */
 protected String buildFullDN(String objectDN, String baseDN) {
   objectDN = Val.chkStr(objectDN).toLowerCase();
   if (objectDN.length() > 0) {
     baseDN = Val.chkStr(baseDN).toLowerCase();
     if (baseDN.length() > 0) {
       boolean bForce = false;
       if (bForce || !objectDN.endsWith("," + baseDN)) {
         objectDN += "," + baseDN;
       }
     }
   }
   return objectDN;
 }
Esempio n. 10
0
 /**
  * Prints argument.
  *
  * @param argName argument name
  * @param argVal argument value
  * @param more flag to indicate if there will be more arguments
  */
 protected void printArg2(String argName, String argVal, boolean more) {
   argName = Val.chkStr(argName);
   argVal = Val.chkStr(argVal);
   if (argName.length() > 0) {
     println(
         "\""
             + Val.escapeStrForJson(argName)
             + "\""
             + sp()
             + ":"
             + sp()
             + (argVal)
             + (more ? "," : ""));
   }
 }
Esempio n. 11
0
 /**
  * Tokenizes a delimited string into a string array.
  *
  * @param tokens the delimited string to tokenize
  * @param delimiter the delimiter
  * @return the string array of tokens
  */
 public static String[] tokenize(String tokens, String delimiter) {
   ArrayList<String> al = new ArrayList<String>();
   tokens = Val.chkStr(tokens);
   if (delimiter == null) {
     delimiter = "";
   } else if (!delimiter.equals(" ")) {
     delimiter = delimiter.trim();
   }
   StringTokenizer st = new StringTokenizer(tokens, delimiter);
   while (st.hasMoreElements()) {
     String s = Val.chkStr((String) st.nextElement());
     al.add(s);
   }
   return al.toArray(new String[0]);
 }
 /**
  * Searches users matching filter in ldap.
  *
  * @param request HTTP request.
  * @param response HTTP response.
  * @param context request context
  * @throws IdentityException if a system error occurs preventing the action
  * @throws IOException if error writing to the buffer
  * @throws NamingException if an LDAP naming exception occurs
  * @throws SQLException
  */
 protected void executeSearchMembers(
     HttpServletRequest request, HttpServletResponse response, RequestContext context)
     throws IdentityException, IOException, NamingException, SQLException {
   String mimeType = "application/json";
   String filter = Val.chkStr(request.getParameter("q"));
   String attributeName = Val.chkStr(request.getParameter("a"));
   if (filter.length() == 0) {
     response.getWriter().write("{ \"response\" : \"noResults\" }");
     return;
   }
   writeCharacterResponse(
       response,
       serializeUsersAsJson(context, filter, attributeName, true),
       "UTF-8",
       mimeType + ";charset=UTF-8");
 }
  /**
   * Executes a delete user action.
   *
   * @param request HTTP request.
   * @param response HTTP response.
   * @param context request context
   * @throws Exception if an exception occurs
   */
  private void executeDeleteUser(
      HttpServletRequest request, HttpServletResponse response, RequestContext context)
      throws Exception {
    try {
      String[] parts = request.getRequestURI().toString().split("/");
      if (parts.length > 0) {
        String userIdentifier = URLDecoder.decode(parts[5].trim(), "UTF-8");
        if (userIdentifier.endsWith(userDIT)) {
          String attempt = Val.chkStr(request.getParameter("attempt"));
          IdentityAdapter idAdapter = context.newIdentityAdapter();
          User user = new User();
          user.setDistinguishedName(userIdentifier);
          idAdapter.readUserProfile(user);
          idAdapter.readUserGroups(user);

          boolean isSelf = checkSelf(context, userIdentifier);
          if ((isSelf && attempt.equals("2")) || !isSelf) {
            idAdapter.deleteUser(user);
            response
                .getWriter()
                .write(msgBroker.retrieveMessage("catalog.identity.deleteUser.success"));
          } else {
            response.getWriter().write("prompt");
          }
        }
      }
    } finally {
    }
  }
  /**
   * Reads user profile from ldap.
   *
   * @param context the current request context (contains the active user)
   * @param request HTTP request.
   * @return user the user whose profile was read
   * @throws IdentityException if a system error occurs preventing the action
   * @throws NamingException if an LDAP naming exception occurs
   * @throws SQLException if a database communication exception occurs
   * @throws CredentialsDeniedException
   * @throws UnsupportedEncodingException
   */
  protected User readUserProfile(RequestContext context, HttpServletRequest request)
      throws Exception {

    IdentityAdapter idAdapter = context.newIdentityAdapter();
    User user = new User();
    String[] parts = request.getRequestURI().toString().split("/");
    String sEncoding = request.getCharacterEncoding();
    if ((sEncoding == null) || (sEncoding.trim().length() == 0)) {
      sEncoding = "UTF-8";
    }

    if (parts.length > 0) {
      String userIdentifier = Val.chkStr(URLDecoder.decode(parts[5].trim(), "UTF-8"));
      if (userIdentifier.endsWith(userDIT)) {
        user.setDistinguishedName(userIdentifier);
        DistinguishedNameCredential dnCredential = new DistinguishedNameCredential();
        dnCredential.setDistinguishedName(userIdentifier);
        user.setCredentials(dnCredential);
      } else if (userIdentifier.length() > 0) {
        user.setCredentials(new UsernameCredential(userIdentifier));
      }
      ((LdapIdentityAdapter) idAdapter).populateUser(context, user);
      return user;
    } else {
      throw new Exception("error");
    }
  }
Esempio n. 15
0
 /**
  * Checks the value of a String to determine the corresponding enum.
  *
  * @param direction the string to check
  * @return the corresponding enum (default is OrderByDirection.asc)
  */
 public static SortDirection checkValue(String direction) {
   try {
     return SortDirection.valueOf(Val.chkStr(direction));
   } catch (IllegalArgumentException ex) {
     return SortDirection.defaultValue();
   }
 }
 public void setFrequencyModeAsString(String frequencyMode) {
   frequencyMode = Val.chkStr(frequencyMode);
   try {
     this.frequencyMode = FrequencyMode.valueOf(frequencyMode.toUpperCase());
   } catch (IllegalArgumentException ex) {
     this.frequencyMode = FrequencyMode.PERIODICAL;
   }
 }
Esempio n. 17
0
 /**
  * Check a string value and ensures that it does not exceed a maximum length.
  *
  * @param s the string to check
  * @param maxLength the maximum length for the string
  * @return the checked string (substring to the max length if applicable)
  */
 public static String chkStr(String s, int maxLength) {
   s = Val.chkStr(s);
   if ((maxLength > 0) && (s.length() > maxLength)) {
     return s.substring(0, maxLength);
   } else {
     return s;
   }
 }
Esempio n. 18
0
 /**
  * Check a string value.
  *
  * @param s the string to check
  * @param defaultVal the default value to return if the string is null or empty
  * @return the checked string (trimmed, default value if the supplied String was null or empty)
  */
 public static String chkStr(String s, String defaultVal) {
   s = Val.chkStr(s);
   if (s.length() == 0) {
     return defaultVal;
   } else {
     return s;
   }
 }
Esempio n. 19
0
  /**
   * Establishes the user associated with the operation.
   *
   * @param context the assertion operation context
   * @throws NotAuthorizedException if authentication was required
   * @throws AsnInsufficientPrivilegeException if the user has insufficient privilege
   * @throws AsnUnestablishedUserException if the user could not be established
   */
  public void establishUser(AsnContext context)
      throws NotAuthorizedException, AsnUnestablishedUserException {

    // initialize
    this.setWasUserEstablished(false);
    AsnOperation operation = context.getOperation();
    User user = context.getRequestContext().getUser();

    // establish the user part of the operation
    if (operation.getUserPart() == null) {
      operation.setUserPart(new AsnUserPart());
    }
    operation.getUserPart().setIPAddress(context.getRequestOptions().getIPAddress());
    AsnAuthPolicy authPolicy = operation.getAuthPolicy();
    if (authPolicy.getAuthenticationRequired()) {
      if ((user == null) || !user.getAuthenticationStatus().getWasAuthenticated()) {
        throw new NotAuthorizedException("Not authorized.");
      }
    }
    if ((user == null) || !user.getAuthenticationStatus().getWasAuthenticated()) {
      operation.getUserPart().setName(AsnConstants.ANONYMOUS_USERNAME);
      this.setWasUserEstablished(true);
    } else {
      String key = Val.chkStr(user.getKey());
      if (key.length() > 0) {
        operation.getUserPart().setKey(key);
        if (user.getLocalID() >= 0) {
          operation.getUserPart().setID("" + user.getLocalID());
          String name = Val.chkStr(user.getName());
          if (name.length() > 0) {
            operation.getUserPart().setName(name);
            this.setWasUserEstablished(true);
          }
        }
      }
    }
    if (!this.getWasUserEstablished()) {
      throw new AsnUnestablishedUserException();
    }

    // check the admin database for a disabled user:ipaddress or user:key

    // check the admin index for moderation privileges

  }
  /**
   * Writes title section.
   *
   * @param record record
   */
  private void writeTitle(SearchResultRecord record) {
    String sUuid = Val.chkStr(record.getUuid());
    String sTitle = Val.chkStr(record.getTitle());

    _writer.println("<div class=\"" + TITLE_STYLE_CLASS + "\">");

    // content type icon
    ResourceLink icon = record.getResourceLinks().getIcon();
    if (icon != null) {
      String sUrl = Val.chkStr(icon.getUrl());
      if ((sUrl.length() > 0) && getShowIcon()) {
        _writer.print("<img src=\"");
        _writer.print(Val.escapeXmlForBrowser(sUrl));
        _writer.print("\" alt=\"");
        _writer.print(Val.escapeXmlForBrowser(icon.getLabel()));
        _writer.print("\" title=\"");
        _writer.print(Val.escapeXmlForBrowser(icon.getLabel()));
        _writer.print("\"/>");
      }
    }

    // title (or uuid if no title)
    sTitle = sTitle.length() > 0 ? sTitle : sUuid;
    _writer.println(Val.escapeXmlForBrowser(sTitle));

    _writer.println("</div>");
  }
 /**
  * Checks value of the string.
  *
  * @param value value
  * @return corresponding target or {@link Target#blank} if value is invalid
  */
 public static Target checkValueOf(String value) {
   value = Val.chkStr(value);
   for (Target t : values()) {
     if (t.name().equalsIgnoreCase(value)) {
       return t;
     }
   }
   return blank;
 }
Esempio n. 22
0
  /**
   * Submit HTTP Request (Both GET and POST). Return InputStream object from the response
   *
   * <p>Submit an HTTP request.
   *
   * @return Response in plain text.
   * @param method HTTP Method. for example "POST", "GET"
   * @param urlString URL to send HTTP Request to
   * @param postdata Data to be posted
   * @param usr Username
   * @param pwd Password
   * @throws IOException in IOException
   * @throws java.net.SocketTimeoutException if connect or read timeout
   */
  public InputStream submitHttpRequest(
      String method, String urlString, String postdata, String usr, String pwd) throws IOException {

    if (LOG.isLoggable(Level.FINER)) {
      LOG.finer("Data being sent.  URL = " + urlString + "\n Data = " + postdata);
    }

    urlString = Utils.chkStr(urlString);
    urlString = urlString.replaceAll("\\n", "");
    urlString = urlString.replaceAll("\\t", "");
    urlString = urlString.replaceAll("\\r", "");
    urlString = urlString.replaceAll(" ", "");

    HttpClientRequest client = HttpClientRequest.newRequest();
    client.setUrl(urlString);
    client.setRetries(1);

    usr = Val.chkStr(usr);
    pwd = Val.chkStr(pwd);
    if (usr.length() > 0 || pwd.length() > 0) {
      CredentialProvider provider = new CredentialProvider(usr, pwd);
      client.getCredentialProvider();
      client.setCredentialProvider(provider);
    }
    if (this.getReadTimeout() > 0) {
      client.setResponseTimeOutMs(this.getReadTimeout());
    }
    if (this.getConnectTimeout() > 0) {
      client.setConnectionTimeMs(this.getConnectTimeout());
    }

    // Send a request
    if (Val.chkStr(method).equalsIgnoreCase("post")) {
      ContentProvider contentProvider = new StringProvider(postdata, "text/xml");
      client.setContentProvider(contentProvider);

    } else {
      client.setMethodName(MethodName.GET);
    }

    String response = client.readResponseAsCharacters();
    LOG.finer(" CSW Response : " + response);
    return new ByteArrayInputStream(response.getBytes("UTF-8"));
  }
 /**
  * Checks if manage user role is restricted to configured geoportal roles.
  *
  * @param context the current request context
  * @return true is the functionality is enabled
  */
 protected boolean checkIfAllowConfigured(RequestContext context) {
   boolean bCheckIfAllowed = false;
   StringAttributeMap umParameters = context.getCatalogConfiguration().getParameters();
   if (umParameters.containsKey("ldap.identity.restrictToConfiguredRoles")) {
     String sCheckIfAllowed =
         com.esri.gpt.framework.util.Val.chkStr(
             umParameters.getValue("ldap.identity.restrictToConfiguredRoles"));
     bCheckIfAllowed = Boolean.valueOf(sCheckIfAllowed);
   }
   return bCheckIfAllowed;
 }
 /**
  * Checks if delete user from ldap is enabled
  *
  * @param context the current request context
  * @return true is the functionality is enabled
  */
 private boolean checkHasDeleteUser(RequestContext context) {
   boolean umHasDeleteUserButton = false;
   StringAttributeMap umParameters = context.getCatalogConfiguration().getParameters();
   if (umParameters.containsKey("ldap.identity.manage.userRoleEnabled")) {
     String umDeleteUserButtonEnabled =
         com.esri.gpt.framework.util.Val.chkStr(
             umParameters.getValue("ldap.identity.manage.userRoleEnabled"));
     umHasDeleteUserButton = Boolean.valueOf(umDeleteUserButtonEnabled);
   }
   return umHasDeleteUserButton;
 }
 /**
  * Checks if user role matches provided groups distinguished name.
  *
  * @param context
  * @param groupDn
  * @return true if managed user role is same as groupDn
  */
 protected boolean checkRole(User user, String groupDn) {
   boolean isSelf = false;
   Groups groups = user.getGroups();
   for (Group group : groups.values()) {
     String dn = Val.chkStr(group.getDistinguishedName());
     if (dn.equals(groupDn)) {
       isSelf = true;
       break;
     }
   }
   return isSelf;
 }
  /**
   * Creates instance of editor.
   *
   * @param harvestRepository repository to be edited
   */
  public HarvestEditor(HrRecord harvestRepository) {
    _harvestRepository = harvestRepository;
    protocols.put(harvestRepository.getProtocol().getKind(), harvestRepository.getProtocol());

    ApplicationContext appCtx = ApplicationContext.getInstance();
    ApplicationConfiguration appCfg = appCtx.getConfiguration();

    String sArcgisDotComAllowed =
        appCfg
            .getCatalogConfiguration()
            .getParameters()
            .getValue("webharvester.agp2agp.arcgisDotCom.allowed");
    this.arcgisDotComAllowed = Val.chkBool(sArcgisDotComAllowed, false);

    String sCrossAllowed =
        appCfg
            .getCatalogConfiguration()
            .getParameters()
            .getValue("webharvester.agp2agp.sameDomain.allowed");
    this.crossAllowed = Val.chkBool(sCrossAllowed, false);
  }
  /**
   * Reads configured roles.
   *
   * @param request HTTP request.
   * @param response HTTP response.
   * @param context request context
   * @throws IdentityException if a system error occurs
   */
  private void executeReadConfigureRoles(
      HttpServletRequest request, HttpServletResponse response, RequestContext context)
      throws Exception {
    String mimeType = "application/json";
    String rolesJson = " { \"configuredRoles\" : [";
    Roles roles = buildSelectableRoles(context);
    ArrayList<String> sortedKeys = new ArrayList<String>(roles.keySet());
    Collections.sort(sortedKeys);
    boolean firstRole = true;
    for (int i = 0; i < sortedKeys.size(); i++) {
      Role role = roles.get(sortedKeys.get(i));
      String roleDn = Val.chkStr(role.getDistinguishedName());
      String roleKey = Val.chkStr(role.getKey());
      String roleName = msgBroker.retrieveMessage(Val.chkStr(role.getResKey()));
      if (!role.isManage()) continue;
      if (!firstRole) {
        rolesJson += ",";
      } else {
        firstRole = false;
      }
      rolesJson +=
          " { \"roleName\" : \""
              + Val.escapeStrForJson(roleName)
              + "\" , \"roleDn\" : \""
              + Val.escapeStrForJson(roleDn)
              + "\" , \"roleKey\" : \""
              + Val.escapeStrForJson(roleKey)
              + "\" }";
    }
    rolesJson += " ] } ";

    writeCharacterResponse(response, rolesJson, "UTF-8", mimeType + ";charset=UTF-8");
  }
  /**
   * Serializes list of ldap users matching filter.
   *
   * @param context the current request context
   * @param filter the user search filter for ldap
   * @return the list of users as json
   * @throws IdentityException if a system error occurs preventing the action
   * @throws NamingException if an LDAP naming exception occurs
   * @throws SQLException
   */
  protected String serializeUsersAsJson(
      RequestContext context, String filter, String attributeName, boolean isMemberSearch)
      throws IdentityException, NamingException, SQLException {
    Users users = new Users();
    int totalMatches = 0;
    if (!isMemberSearch) {
      HashMap<String, Object> resultsMap = buildUsersList(context, filter, null);
      users = (Users) resultsMap.get("topUserMatches");
      totalMatches = (Integer) resultsMap.get("totalMatches");
    } else if (isMemberSearch && attributeName != null) {
      Roles configuredRoles = context.getIdentityConfiguration().getConfiguredRoles();
      Role role = configuredRoles.get(attributeName);
      String sDn = role.getDistinguishedName();
      IdentityAdapter idAdapter = context.newIdentityAdapter();
      users = idAdapter.readGroupMembers(sDn);
      totalMatches = users.size();
      users.sort();
    } else {
      IdentityAdapter idAdapter = context.newIdentityAdapter();
      Users members = idAdapter.readGroupMembers(filter);
      for (User u : members.values()) {
        users.add(u);
      }
      users.sort();
      totalMatches = users.size();
    }

    String usersJson =
        "{ \"totalUsers\" : \""
            + totalMatches
            + "\" ,\"topUsers\" : \""
            + users.size()
            + "\" , \"users\": [";
    boolean firstUser = true;
    for (User user : users.values()) {
      String userName = user.getName();
      String dn = user.getKey();
      if (!firstUser) {
        usersJson += ",";
      } else {
        firstUser = false;
      }
      usersJson +=
          " { \"dn\" : \""
              + dn
              + "\" , \"userName\" : \""
              + Val.escapeStrForJson(userName)
              + "\" }";
    }
    usersJson += " ] }";
    return usersJson;
  }
Esempio n. 29
0
 /**
  * Loads the XML document object model (org.w3c.dom.Document).
  *
  * @throws Exception if an exception occurs
  */
 public Document loadDom() {
   Document dom = null;
   try {
     URL url = this.makeUrl();
     InputSource src = new InputSource(url.toExternalForm());
     dom = DomUtil.makeDomFromSource(src, true);
     if (this.getIsRoot()) {
       this.setBaseLocations(new ArrayList<URI>());
       String baseLoc = url.toExternalForm();
       int nIdx = baseLoc.lastIndexOf("/");
       if (nIdx != -1) baseLoc = baseLoc.substring(0, nIdx);
       this.getBaseLocations().add(new URI(baseLoc + "/"));
       this.inheritBaseLocations(dom);
     }
   } catch (Exception e) {
     String msg = "Error loading XML file: " + Val.chkStr(this.getLocation());
     msg += ", " + Val.chkStr(e.toString());
     LOGGER.log(Level.CONFIG, msg, e);
     throw new ConfigurationException(msg, e);
   }
   return dom;
 }
  /**
   * Checks if manage user role is enabled
   *
   * @param context the current request context
   * @return true is the functionality is enabled
   */
  protected boolean checkHasManageUsers(RequestContext context) {
    boolean umHasDeleteUserLink = false;
    UsernamePasswordCredentials upc =
        context.getIdentityConfiguration().getSimpleConfiguration().getServiceAccountCredentials();
    if (upc != null) return umHasDeleteUserLink;

    StringAttributeMap umParameters = context.getCatalogConfiguration().getParameters();
    if (umParameters.containsKey("ldap.identity.manage.userRoleEnabled")) {
      String umHasDeleteUserLinkEnabled =
          com.esri.gpt.framework.util.Val.chkStr(
              umParameters.getValue("ldap.identity.manage.userRoleEnabled"));
      umHasDeleteUserLink = Boolean.valueOf(umHasDeleteUserLinkEnabled);
    }
    return umHasDeleteUserLink;
  }