/*
   * Method responsible for generating appropriate REST URLs
   *
   * @param ProfileEntity ( Ref Class : ProfileEntity )
   * @param ProfileType ( Ref Class : ProfileType )
   * @param params : ( Ref Class : ProfileParams )
   * @return String
   */
  protected String resolveProfileUrl(
      String profileEntity, String profileType, Map<String, String> params) {
    if (logger.isLoggable(Level.FINEST)) {
      logger.entering(sourceClass, "resolveCommunityUrl", profileEntity + profileType);
    }

    StringBuilder proBaseUrl = new StringBuilder(ProfileBaseUrl);
    if (StringUtil.isEmpty(profileEntity)) {
      profileEntity = ProfileEntity.NONADMIN.getProfileEntityType(); // Default
      // Entity
      // Type
    }
    if (StringUtil.isEmpty(profileType)) {
      profileType = ProfileType.GETPROFILE.getProfileType(); // Default
      // Profile
      // Type
    }
    if (AuthUtil.INSTANCE.getAuthValue(endpoint).equalsIgnoreCase("oauth")) {
      if (profileEntity.equalsIgnoreCase(ProfileEntity.NONADMIN.getProfileEntityType())) {
        proBaseUrl.append(seperator).append("oauth");
      }
    }
    if (profileEntity.equalsIgnoreCase("")) { // if it is non admin API then
      // no need to append anythin
      proBaseUrl.append(seperator).append(profileType);
    } else {
      proBaseUrl.append(profileEntity).append(seperator).append(profileType);
    }

    // Add required parameters
    if (null != params) {
      if (params.size() > 0) {
        proBaseUrl.append("?");
        boolean setSeperator = false;
        for (Map.Entry<String, String> param : params.entrySet()) {
          if (setSeperator) {
            proBaseUrl.append("&");
          }
          String paramvalue = "";
          try {
            paramvalue = URLEncoder.encode(param.getValue(), "UTF-8");
          } catch (UnsupportedEncodingException e) {
          }
          proBaseUrl.append(param.getKey() + "=" + paramvalue);
          setSeperator = true;
        }
      }
    }

    if (logger.isLoggable(Level.FINEST)) {
      logger.log(Level.FINEST, Messages.ProfileInfo_7 + proBaseUrl.toString());
    }
    return proBaseUrl.toString();
  }
 protected void writeCollapseAll(
     FacesContext context, ResponseWriter w, UIPagerExpand pager, FacesDataIterator dataIterator)
     throws IOException {
   String text = pager.getCollapseText();
   if (StringUtil.isEmpty(text)) {
     text = "Collapse all"; // $NLS-PagerExpandRenderer.CollapseAll-1$
   }
   if (StringUtil.isNotEmpty(text)) {
     w.startElement("li", null); // $NON-NLS-1$
     boolean selected = pager.isCollapseAll();
     if (selected) {
       w.writeAttribute("class", "active", null); // $NON-NLS-1$ $NON-NLS-2$
     }
     w.startElement("a", null);
     String clientId = pager.getClientId(context);
     String sourceId = clientId + "_ca"; // $NON-NLS-1$
     w.writeAttribute("id", sourceId, null); // $NON-NLS-1$
     w.writeAttribute("href", "javascript:;", null); // $NON-NLS-1$ $NON-NLS-2$
     // $NON-NLS-2$
     setupSubmitOnClick(context, w, pager, dataIterator, clientId, sourceId);
     w.writeText(text, null);
     w.endElement("a");
     w.endElement("li"); // $NON-NLS-1$
   }
 }
Exemple #3
0
 public String generateValueList(String list) {
   if (StringUtil.isEmpty(list)) {
     return "";
   }
   StringBuilder b = new StringBuilder();
   b.append("<ul>");
   String[] values = StringUtil.splitString(list, '\n');
   for (int i = 0; i < values.length; i++) {
     String s = values[i];
     if (StringUtil.isNotEmpty(s)) {
       String name = s;
       String desc = null;
       int pos = s.indexOf('|');
       if (pos >= 0) {
         name = s.substring(0, pos);
         desc = s.substring(pos + 1);
       }
       b.append("<li>");
       b.append("<b>");
       b.append(TextUtil.toXMLString(name));
       b.append("</b>");
       if (StringUtil.isNotEmpty(desc)) {
         b.append(": ");
         b.append(TextUtil.toXMLString(desc));
       }
       b.append("</li>");
     }
   }
   b.append("</ul>");
   return b.toString();
 }
  public String getPostId() {
    String id = null;
    // First check the URL
    Map<String, String> param = FrameworkUtils.getParam();
    if (StringUtil.isNotEmpty(param.get("id"))) { // $NON-NLS-1$
      id = param.get("id"); // $NON-NLS-1$
    }

    if (StringUtil.isEmpty(id)) {
      // Then check the path info
      String pathInfo = FacesContext.getCurrentInstance().getExternalContext().getRequestPathInfo();
      if (StringUtil.isNotEmpty(pathInfo)) {
        id = pathInfo.substring(1);
      }
    }

    if (StringUtil.isNotEmpty(id)) {
      if (!DominoUtils.isUnid(id)) {
        // Then it must be the URL slug - look it up in the view
        AbstractModelList<Post> posts =
            Post.Manager.get().getNamedCollection("All", null); // $NON-NLS-1$
        posts.setResortOrder("$Key", TabularDataModel.SORT_ASCENDING); // $NON-NLS-1$
        return posts.getByKey(id).getId();
      } else {
        return id;
      }
    }

    return "new"; //$NON-NLS-1$
  }
Exemple #5
0
 public static String getDefaultRendererType(ThemeControl c, String defaultRenderer) {
   if (useTheme852 /*ExtLibUtil.isXPages852()*/) {
     // 852: we assume OneUI
     if (!isOneUITheme(FacesContextEx.getCurrentInstance())) {
       // or we could actually check to see if it's OneUI
       return defaultRenderer;
     }
     if (OneUIRendererTypes == null) {
       synchronized (ThemeUtil.class) {
         if (OneUIRendererTypes == null) {
           OneUIRendererTypes = buildOneUIMap();
         }
       }
     }
     String rt = OneUIRendererTypes.get(c.getStyleKitFamily());
     if (StringUtil.isEmpty(rt)) {
       return defaultRenderer;
     }
     return rt;
   } else {
     // Post 852: we assume that the renderer type is forced by a theme
     // So we just set the default renderer here
     return defaultRenderer;
   }
 }
 @Override
 public void setUrl(String url) {
   super.setUrl(url);
   // Make the URL the service name if not already set
   if (StringUtil.isEmpty(oaProvider.getServiceName())) {
     oaProvider.setServiceName(url);
   }
 }
  /**
   * Wrapper method to get common colleagues of two users
   *
   * @param sourceId userid or email of first user
   * @param targetId userid or email of second user
   * @return Collection<ConnectionEntry>
   * @throws ProfileServiceException
   */
  private Collection<ConnectionEntry> getColleaguesInCommon(
      String sourceId, String targetId, Map<String, String> parameters)
      throws ProfileServiceException {

    if (logger.isLoggable(Level.FINEST)) {
      logger.entering(sourceClass, "checkColleague");
    }
    if (StringUtil.isEmpty(sourceId)) {
      throw new IllegalArgumentException(Messages.InvalidArgument_4);
    }
    if (StringUtil.isEmpty(targetId)) {
      throw new IllegalArgumentException(Messages.InvalidArgument_5);
    }
    Document data = null;
    if (parameters == null) {
      parameters = new HashMap<String, String>();
    }
    String url =
        resolveProfileUrl(
            ProfileEntity.NONADMIN.getProfileEntityType(),
            ProfileType.CONNECTIONS_IN_COMMON.getProfileType());
    if (isEmail(sourceId)) {
      StringBuilder value = new StringBuilder(sourceId);
      value = value.append(",").append(targetId);
      parameters.put(ProfileRequestParams.EMAIL, value.toString());
    } else {

      StringBuilder value = new StringBuilder(sourceId);
      value = value.append(",").append(targetId);
      parameters.put(ProfileRequestParams.USERID, value.toString());
    }
    parameters.put("connectionType", "colleague");

    data = executeGet(url, parameters, ClientService.FORMAT_XML);
    Collection<ConnectionEntry> colleaguesInCommon =
        Converter.returnConnectionEntries(data, "connectionEntry");

    if (logger.isLoggable(Level.FINEST)) {
      logger.exiting(sourceClass, "getColleagues");
    }
    return colleaguesInCommon;
  }
  /**
   * Wrapper method to get check if two users are colleagues
   *
   * @param sourceId userid or email of first user
   * @param targetId userid or email of second user
   * @param parameters list of query string parameters to pass to API
   * @return ConnectionEntry
   * @throws ProfileServiceException
   */
  private ConnectionEntry checkColleague(
      String sourceId, String targetId, Map<String, String> parameters)
      throws ProfileServiceException {

    if (logger.isLoggable(Level.FINEST)) {
      logger.entering(sourceClass, "checkColleague");
    }
    if (StringUtil.isEmpty(sourceId)) {
      throw new IllegalArgumentException(Messages.InvalidArgument_4);
    }
    if (StringUtil.isEmpty(targetId)) {
      throw new IllegalArgumentException(Messages.InvalidArgument_5);
    }
    Document data = null;
    if (parameters == null) {
      parameters = new HashMap<String, String>();
    }
    String url =
        resolveProfileUrl(
            ProfileEntity.NONADMIN.getProfileEntityType(), ProfileType.CONNECTION.getProfileType());
    if (isEmail(sourceId)) {
      parameters.put(ProfileRequestParams.SOURCEEMAIL, sourceId);
    } else {
      parameters.put(ProfileRequestParams.SOURCEUSERID, sourceId);
    }
    if (isEmail(targetId)) {
      parameters.put(ProfileRequestParams.TARGETEMAIL, targetId);
    } else {
      parameters.put(ProfileRequestParams.TARGETUSERID, targetId);
    }
    parameters.put("connectionType", "colleague");

    data = executeGet(url, parameters, ClientService.FORMAT_XML);
    ConnectionEntry connection =
        Converter.returnConnectionEntries(data, "connectionEntry").iterator().next();

    if (logger.isLoggable(Level.FINEST)) {
      logger.exiting(sourceClass, "getColleagues");
    }
    return connection;
  }
  @Override
  protected void writeFormLayout(FacesContext context, ResponseWriter w, FormLayout c)
      throws IOException {
    ComputedFormData formData = createFormData(context, c);
    String style = c.getStyle();
    String styleClass = c.getStyleClass();

    w.startElement("div", c); // $NON-NLS-1$
    String styleProp = (String) getProperty(PROP_FORMCONTAINERSTYLE);
    if (StringUtil.isNotEmpty(styleProp)) {
      style = ExtLibUtil.concatStyles(style, styleProp);
    }
    if (!StringUtil.isEmpty(style)) {
      w.writeAttribute("style", style, null); // $NON-NLS-1$
    }
    String styleClassProp = (String) getProperty(PROP_FORMCONTAINERSTYLECLASS);
    if (StringUtil.isNotEmpty(styleClassProp)) {
      styleClass = ExtLibUtil.concatStyleClasses(styleClass, styleClassProp);
    }
    if (!StringUtil.isEmpty(styleClass)) {
      w.writeAttribute("class", styleClass, null); // $NON-NLS-1$
    }
    w.writeAttribute("id", c.getClientId(context), null); // $NON-NLS-1$

    newLine(w);
    writeErrorSummary(context, w, c, formData);
    writeHeader(
        context, w,
        c); // TODO:this is sort of messed up in how it is placing its divs, needs to be fixed
    w.startElement("div", c); // $NON-NLS-1$
    writeMainTableTag(context, w, c);
    newLine(w);

    writeForm(context, w, c, formData);

    w.endElement("div"); // $NON-NLS-1$
    newLine(w);
    writeFooter(context, w, c);
    w.endElement("div"); // $NON-NLS-1$
    newLine(w);
  }
Exemple #10
0
  /**
   * Return true if a Panel was created on the page i.e. could find ul, multiple li's
   *
   * @return
   */
  protected boolean checkPanel(PanelResultPage resultPage, String snippetId) {
    Trace.log("Panel result page: " + resultPage.getText());

    String photoUrl = resultPage.getPhotoUrl();
    Assert.assertFalse("Invalid photo url", StringUtil.isEmpty(photoUrl));

    String[] details = resultPage.getDetails();
    Assert.assertFalse("Invalid details", details == null || details.length == 0);
    Assert.assertEquals("Invalid details", 4, details.length);

    return true;
  }
 @Override
 public void checkValid() throws SBTException {
   super.checkValid();
   if (StringUtil.isEmpty(oaProvider.getConsumerKey())) {
     throw new SBTException(null, "The Endpoint consumer key is empty, class {0}", getClass());
   }
   if (StringUtil.isEmpty(oaProvider.getConsumerSecret())) {
     throw new SBTException(null, "The Endpoint consumer secret is empty, class {0}", getClass());
   }
   if (StringUtil.isEmpty(oaProvider.getAuthorizationURL())) {
     throw new SBTException(
         null, "The Endpoint authorization URL is empty, class {0}", getClass());
   }
   if (StringUtil.isEmpty(oaProvider.getRequestTokenURL())) {
     throw new SBTException(
         null, "The Endpoint request token URL is empty, class {0}", getClass());
   }
   if (StringUtil.isEmpty(oaProvider.getAccessTokenURL())) {
     throw new SBTException(null, "The Endpoint access token URL is empty, class {0}", getClass());
   }
 }
  /**
   * Replace the first occurrence of a string within a source string.
   *
   * @param source the source string
   * @param value the string to search for
   * @param replace the string replacement
   * @return the resulting string
   * @ibm-api
   */
  public static final String replaceFirst(String source, String value, String replace) {
    if (StringUtil.isEmpty(source) || StringUtil.isEmpty(value)) {
      return ""; //$NON-NLS-1$
    }
    if (replace == null) {
      replace = ""; // $NON-NLS-1$
    }
    int idx = source.indexOf(value);
    if (idx >= 0) {
      // Initialize the buffer with the begining of the string
      FastStringBuffer buffer = new FastStringBuffer();
      buffer.append(source, 0, idx);
      // Append the change to the str
      buffer.append(replace);
      int next = idx + value.length();
      // Append the string up to the next occurence of the value
      buffer.append(source, next, source.length());

      return buffer.toString();
    }

    // Nothing changed in the string
    return source;
  }
 /**
  * Get a customer list by the organization name.
  *
  * @param orgName
  * @return
  * @throws BssException
  * @throws {@link IllegalArgumentException}
  */
 public EntityList<JsonEntity> getCustomerByOrgName(String orgName) throws BssException {
   if (StringUtil.isEmpty(orgName)) {
     throw new IllegalArgumentException("Invalid organization name");
   }
   try {
     String serviceUrl =
         BssUrls.API_RESOURCE_GET_CUSTOMER_BY_ORGNAME.format(
             this, new NamedUrlPart("orgName", orgName));
     return (EntityList<JsonEntity>) getEntities(serviceUrl, null, getJsonFeedHandler());
   } catch (Exception e) {
     throw new BssException(
         e,
         "Error retrieving customer list by organization name {0} caused by {1]",
         orgName,
         e.getMessage());
   }
 }
 /**
  * Get a customer list by the email address of the subscriber.
  *
  * @param subscriberEmail
  * @return
  * @throws BssException
  * @throws {@link IllegalArgumentException}
  */
 public EntityList<JsonEntity> getCustomersBySubscriberEmail(String subscriberEmail)
     throws BssException {
   if (StringUtil.isEmpty(subscriberEmail)) {
     throw new IllegalArgumentException("Invalid subscriber email address");
   }
   try {
     String serviceUrl =
         BssUrls.API_RESOURCE_GET_CUSTOMERS_BY_SUBSCIBER_EMAIL.format(
             this, new NamedUrlPart("emailAddress", subscriberEmail));
     return (EntityList<JsonEntity>) getEntities(serviceUrl, null, getJsonFeedHandler());
   } catch (Exception e) {
     throw new BssException(
         e,
         "Error retrieving customer list by subscriber email {0} caused by {1}",
         subscriberEmail,
         e.getMessage());
   }
 }
 public static List<String> listTables(
     Connection c, String schema, String tableName, String[] types) throws SQLException {
   final ResultSet tables = c.getMetaData().getTables(null, schema, tableName, types);
   try {
     final ArrayList<String> l = new ArrayList<String>();
     while (tables.next()) {
       final String sc = tables.getString("TABLE_SCHEM"); // $NON-NLS-1$
       final String tb = tables.getString("TABLE_NAME"); // $NON-NLS-1$
       if (StringUtil.isEmpty(sc)) {
         l.add(tb);
       } else {
         l.add(StringUtil.format("{0}.{1}", sc, tb));
       }
     }
     return l;
   } finally {
     tables.close();
   }
 }
 @Override
 protected void writeErrorSummaryMainText(
     FacesContext context, ResponseWriter w, FormLayout c, FacesMessage.Severity sev)
     throws IOException {
   w.startElement("h1", c); // $NON-NLS-1$
   String style = (String) getProperty(PROP_ERRORSUMMARYSTYLE);
   if (StringUtil.isNotEmpty(style)) {
     w.writeAttribute("style", style, null); // $NON-NLS-1$
   }
   String cls = (String) getProperty(PROP_ERRORSUMMARYCLASS);
   if (StringUtil.isNotEmpty(cls)) {
     w.writeAttribute("class", cls, null); // $NON-NLS-1$
   }
   String mainText = c.getErrorSummaryText();
   if (StringUtil.isEmpty(mainText)) {
     mainText = (String) getProperty(PROP_ERRORSUMMARYMAINTEXT);
   }
   writeErrorMessage(context, w, c, mainText);
   w.endElement("h1"); // $NON-NLS-1$
 }
Exemple #17
0
  protected void writeFile(File folder, String fileName, String contents) {
    try {
      if (StringUtil.isEmpty(contents)) {
        return;
      }

      File file = (new File(folder, fileName)).getAbsoluteFile();
      if (file.exists()) {
        if (!environment.isOverwriteTestdata()) {
          return;
        } else {
          file.delete();
        }
      }
      file.createNewFile();
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(contents.getBytes());
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #18
0
 /**
  * Wrapper method to get profile of a user, it makes the network call to fetch the Profile's of a
  * user based on load parameter being true/false.
  *
  * @param userId unique identifier of User , it can either be email or id
  * @param loaded if true, fetches profile content from server and populates the data member of
  *     {@link Profile} with the fetched content
  * @return Profile
  * @throws ProfileServiceException
  */
 public Profile getProfile(String userId, boolean loaded) throws ProfileServiceException {
   if (logger.isLoggable(Level.FINEST)) {
     logger.entering(sourceClass, "getProfile", new Object[] {userId, loaded});
   }
   if (StringUtil.isEmpty(userId)) {
     throw new IllegalArgumentException(Messages.InvalidArgument_1);
   }
   Profile profile = new Profile(this, userId);
   if (loaded) {
     load(profile);
   }
   if (logger.isLoggable(Level.FINEST)) {
     String log = "";
     if (profile.getId() != null) {
       log = Messages.GetProfileInfo_1;
     } else {
       log = Messages.GetProfileInfo_2;
     }
     logger.exiting(sourceClass, "getProfile", log);
   }
   return profile;
 }
  private void renderServiceGet() throws ServiceException {
    try {
      DatabaseCollectionParameters parameters = getParameters();
      String contentType = "";
      if (StringUtil.isEmpty(contentType)) {
        contentType = HttpServiceConstants.CONTENTTYPE_APPLICATION_JSON;
      }
      getHttpResponse().setContentType(contentType);
      getHttpResponse().setCharacterEncoding(HttpServiceConstants.ENCODING_UTF8);

      Writer writer = new OutputStreamWriter(getOutputStream(), HttpServiceConstants.ENCODING_UTF8);
      boolean compact = parameters.isCompact();
      JsonWriter jwriter = new JsonWriter(writer, compact);

      JsonDatabaseCollectionContent content =
          factory.createDatabaseCollectionContent(
              this.defaultSession, "", RESOURCE_PATH); // $NON-NLS-1$
      content.writeDatabaseCollection(jwriter);

    } catch (UnsupportedEncodingException e) {
      throw new ServiceException(e, "");
    }
  }
  // This function is being overridden to provide style/class to tds...probably
  // should be bubbled up to the actual general FormTableRenderer
  @Override
  protected void writeFormRowData(
      FacesContext context,
      ResponseWriter w,
      FormLayout c,
      ComputedFormData formData,
      UIFormLayoutRow row,
      UIInput edit,
      ComputedRowData rowData)
      throws IOException {
    w.startElement("div", c); // $NON-NLS-1$

    String fieldStyle = row.getStyle();
    if (StringUtil.isEmpty(fieldStyle)) {
      fieldStyle = (String) getProperty(PROP_FIELDROWSTYLE);
    }
    if (StringUtil.isNotEmpty(fieldStyle)) {
      w.writeAttribute("style", fieldStyle, null); // $NON-NLS-1$
    }
    String fieldClass = row.getStyleClass();
    if (StringUtil.isEmpty(fieldClass)) {
      fieldClass = (String) getProperty(PROP_FIELDROWCLASS);
    }
    if (StringUtil.isNotEmpty(fieldClass)) {
      w.writeAttribute("class", fieldClass, null); // $NON-NLS-1$
    }

    // TODO: I think this section is dead code. Look into that.
    boolean rowError = false;
    if (edit != null) {
      // Write the error messages, if any
      if (!formData.isDisableRowError()) {
        Iterator<FacesMessage> msg =
            ((DominoFacesContext) context).getMessages(edit.getClientId(context));
        if (msg.hasNext()) {
          rowError = true;
        }
      }
    }

    boolean hasLabel = rowData.hasLabel();
    boolean labelAbove = rowData.isLabelAbove();

    // Write the label
    w.startElement("div", c); // $NON-NLS-1$
    String tdStyle = (String) getProperty(PROP_FIELDCOLUMNSTYLE);
    if (StringUtil.isNotEmpty(tdStyle)) {
      w.writeAttribute("style", tdStyle, null); // $NON-NLS-1$
    }
    // if we have an error, assign the appropriate classes
    String tdClass =
        hasLabel
            ? (String) getProperty(PROP_FIELDCOLUMNSTYLECLASS)
            : (String) getProperty(PROP_FIELDEDITNOLABELCLASS);
    tdClass =
        (rowError)
            ? ExtLibUtil.concatStyleClasses(
                (String) getProperty(PROP_ERRORROWTITLESTYLECLASS), tdClass)
            : tdClass;
    if ((TypedUtil.getChildren(row).get(0) instanceof XspInputTextarea
            || TypedUtil.getChildren(row).get(0) instanceof UIDojoTextarea)
        && getProperty(PROP_TEXTAREALABELCLASS)
            != null) { // if our row contains a textarea component, we need a special label class
      tdClass =
          ExtLibUtil.concatStyleClasses(tdClass, (String) getProperty(PROP_TEXTAREALABELCLASS));
    }
    if (StringUtil.isNotEmpty(tdClass)) {
      w.writeAttribute("class", tdClass, null); // $NON-NLS-1$
    }
    if (hasLabel) {
      String lblStyle = (String) getProperty(PROP_FIELDLABELSTYLE);
      String lblClass = (String) getProperty(PROP_FIELDLABELCLASS);
      if (labelAbove) {
        w.startElement("div", c); // $NON-NLS-1$
      } else {
        String width = row.getLabelWidth();
        if (StringUtil.isEmpty(width)) {
          width = formData.getLabelWidth();
        }
        if (StringUtil.isEmpty(width)) {
          width = (String) getProperty(PROP_FIELDLABELWIDTH);
        }
        if (StringUtil.isNotEmpty(width)) {
          lblStyle =
              ExtLibUtil.concatStyles(
                  "width:" + width, (String) getProperty(PROP_FIELDLABELSTYLE)); // $NON-NLS-1$
        }
      }
      if (StringUtil.isNotEmpty(lblStyle)) {
        w.writeAttribute("style", lblStyle, null); // $NON-NLS-1$
      }
      if (StringUtil.isNotEmpty(lblClass)) {
        w.writeAttribute("class", lblClass, null); // $NON-NLS-1$
      }
      String label = row.getLabel();
      writeFormRowLabel(context, w, c, formData, row, edit, label);
      if (labelAbove) {
        if (c.isFieldHelp()) {
          writeFormRowHelp(context, w, c, row, edit);
        }
        w.endElement("div"); // $NON-NLS-1$
        w.startElement("div", c); // $NON-NLS-1$
      } else {
        w.endElement("div"); // $NON-NLS-1$
        w.startElement("div", c); // $NON-NLS-1$
      }
    }

    String editStyle =
        (hasLabel && !labelAbove)
            ? ExtLibUtil.concatStyles(
                (String) getProperty(PROP_FORMROWEDITSTYLE),
                (String) getProperty(PROP_FIELDEDITSTYLE))
            : (String) getProperty(PROP_FIELDEDITSTYLE);
    if (StringUtil.isNotEmpty(editStyle)) {
      w.writeAttribute("style", editStyle, null); // $NON-NLS-1$
    }
    String editClass = (String) getProperty(PROP_FIELDEDITCLASS);
    if (TypedUtil.getChildren(row).get(0) instanceof XspInputTextarea
        || TypedUtil.getChildren(row).get(0) instanceof UIDojoTextarea) {
      editClass =
          ExtLibUtil.concatStyleClasses(editClass, (String) getProperty(PROP_TEXTAREASTYLECLASS));
    }
    if (StringUtil.isNotEmpty(editClass)) {
      w.writeAttribute("class", editClass, null); // $NON-NLS-1$
    }

    writeFormRowDataField(context, w, c, row, edit);

    if (hasLabel) {
      if (labelAbove) {
        w.endElement("div"); // $NON-NLS-1$
      }
      // Write the help
      if (hasLabel) {
        if (!labelAbove) {
          if (c.isFieldHelp()) {
            w.startElement("div", c); // $NON-NLS-1$
            writeFormRowHelp(context, w, c, row, edit);
            w.endElement("div"); // $NON-NLS-1$
          }
        }
      }
    }

    w.endElement("div"); // $NON-NLS-1$
    w.endElement("div"); // $NON-NLS-1$
  }
 @Override
 public String getProperty(String propertyName) {
   String property = System.getProperty(propertyName);
   return StringUtil.isEmpty(property) ? getProperty(propertyName, null) : property;
 }
Exemple #22
0
 /*
  * Method to check if the userid is email
  * <p>
  * Current check is based on finding @ in the userid.
  *
  * @param userId
  * @return boolean
  */
 protected boolean isEmail(String userId) {
   if (StringUtil.isEmpty(userId)) {
     return false;
   }
   return userId.contains("@");
 }
  // === continue code from InputRendererUtil ===
  // ClientSide validation
  // com.ibm.xsp.renderkit.html_basic.InputRendererUtil.generateClientSideValidation(FacesContext,
  // UIInput, ResponseWriter)
  private void generateClientSideValidation(
      FacesContext context, UIInput uiInput, ResponseWriter writer) throws IOException {
    // Check if the input field is required
    boolean required = uiInput.isRequired();
    Converter c = InputRendererUtil.findConverter(context, uiInput);
    Validator[] v = uiInput.getValidators();

    // Check if it might make sense to generate a function
    boolean validate = required;
    if (!validate) {
      validate = c instanceof ClientSideConverter;
    }
    if (!validate) {
      for (int i = 0; i < v.length; i++) {
        validate = v[i] instanceof ClientSideValidator;
        if (validate) {
          break;
        }
      }
    }

    if (validate) {
      // This flag is maintained if we actually need to generate the function
      // Some converter/validator may not actually generate any client code, depending on their
      // parameters
      validate = false;

      StringBuilder b = new StringBuilder(128);
      b.append("XSP.attachValidator("); // $NON-NLS-1$
      JavaScriptUtil.addString(b, uiInput.getClientId(context));

      // Add the required flag
      if (required) {
        b.append(",new XSP.RequiredValidator("); // $NON-NLS-1$
        JavaScriptUtil.addMessage(b, InputRendererUtil.getRequiredMessage(context, uiInput));
        b.append(")");
        validate = true;
      } else {
        b.append(",null"); // $NON-NLS-1$
      }

      // Add the converter
      if (c instanceof ClientSideConverter) {
        ClientSideConverter clientSideConverter = (ClientSideConverter) c;
        // TODO this is handling of converterRenderer
        // differs from the original implementation in InputRendererUtil.
        String s;
        Renderer renderer =
            FacesUtil.getRenderer(context, uiInput.getFamily(), uiInput.getRendererType());
        ClientSideConverter converterRenderer =
            (ClientSideConverter) FacesUtil.getRendererAs(renderer, ClientSideConverter.class);
        if (null != converterRenderer) {
          // if the control renderer implements ClientSideConverter
          // delegate to the renderer instead of to the converter.
          s = converterRenderer.generateClientSideConverter(context, uiInput);
        } else {
          s = clientSideConverter.generateClientSideConverter(context, uiInput);
        }
        if (StringUtil.isNotEmpty(s)) {
          b.append(",");
          b.append(s); // not JSUtil because contains client script.
          validate = true;
        } else {
          b.append(",null"); // $NON-NLS-1$
        }
      } else {
        b.append(",null"); // $NON-NLS-1$
      }

      // And add the validator
      for (int i = 0; i < v.length; i++) {
        if (v[i] instanceof ClientSideValidator) {
          String s = ((ClientSideValidator) v[i]).generateClientSideValidation(context, uiInput);
          if (StringUtil.isNotEmpty(s)) {
            b.append(",");
            b.append(s); // not JSUtil because contains client script.
            validate = true;
          }
        }
      }

      // Finally, check for multiple values
      String multiSep = null;
      if (uiInput instanceof UIInputEx) {
        multiSep = ((UIInputEx) uiInput).getMultipleSeparator();
      }
      if (c instanceof ListConverter) {
        multiSep = ((ListConverter) c).getDelimiter();
        if (StringUtil.isEmpty(multiSep)) {
          multiSep = ","; // $NON-NLS-1$
        }
      }
      if (StringUtil.isNotEmpty(multiSep)) {
        b.append(",");
        JSUtil.addString(b, multiSep);
      }

      b.append(");");

      // get the scriptcollector component (needed to add script blocks the the rendered output).
      if (validate) {
        JavaScriptUtil.addScriptOnLoad(b.toString());
      }
    }
  }
  private Object getAsObject(
      FacesContext context, UIInput input, DateTimeConverter converter, String value) {
    if (StringUtil.isEmpty(value)) {
      return null;
    }
    TimeZone tz = converter.getTimeZone();

    // If the date is sent as time, then assume today's date in the browser TZ
    // So we'll have the proper conversion done. If we don't do that, then java
    // uses 1/1/70 and it has an issue when rendering it back in summer, as it leads to
    // one hour difference. This is also in sync with what the Notes backend API does
    int expectedType = getValueType(input);
    value = mutateSubmittedToExpectedFormat(context, input, converter, value, expectedType);
    if (value.startsWith("T")) {
      SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); // $NON-NLS-1$
      fmt.setTimeZone(tz);
      value = fmt.format(new Date()) + value;
    }

    // assume this is a string in ISO format
    // In this case, dojo returns the right date but with a timezone specification computed
    // using the browser information. Unfortunately, it doesn't support the daylight savings
    // So that lead to a wrong time zone (http://trac.dojotoolkit.org/ticket/588)
    // A solution is to ignore the timezone provided by dojo.
    // But the date should be converted to the user TimeZone

    long dt;
    try {
      dt = XMIConverter.readXMIDateStrict(value, false, true);
    } catch (XMLException ex) {
      // TODO in 9.0.2, should update this to handle message changes for SPR#MKEE7TXMLG
      String message;
      int type = expectedType;
      if (type == TYPE_DATE) {
        message = getMessageDate();
      } else if (type == TYPE_TIME) {
        message = getMessageTime();
      } else {
        message = getMessageBoth();
      }
      throw new ConverterException(new FacesMessage(message), ex);
    }

    long offset = 0;
    TimeZone clientTimeZone = tz;
    TimeZone serverTimeZone = TimeZone.getDefault();
    if (!serverTimeZone.equals(clientTimeZone)) {
      // SPR#MKEE9HYGXB cannot use timeZone.getRawOffset()
      // because client timezone is-summerTime-ness and the
      // server timezone is-summerTime-ness may be different,
      // so using the raw offset leads to problems during the
      // period where one timezone has changed to summer time
      // but the other timezone has not.
      Date serverNow = new Date();
      Date clientNow = java.util.Calendar.getInstance(clientTimeZone).getTime();
      offset =
          serverTimeZone.getOffset(serverNow.getTime())
              - clientTimeZone.getOffset(clientNow.getTime());
    }
    dt += offset;
    Date date = new Date(dt);
    return date;
  }
Exemple #25
0
  /**
   * Wrapper method to update a User's profile photo
   *
   * @param Profile
   * @return returns true, if profile photo is updated
   * @throws ProfileServiceException
   */
  public boolean updateProfilePhoto(Profile profile) throws ProfileServiceException {
    if (logger.isLoggable(Level.FINEST)) {
      logger.entering(sourceClass, "updatePhoto", profile.toString());
    }
    if (profile == null) {
      throw new IllegalArgumentException(Messages.InvalidArgument_3);
    }
    boolean returnVal = false;

    Map<String, String> parameters = new HashMap<String, String>();
    if (isEmail(profile.getReqId())) {
      parameters.put(ProfileRequestParams.EMAIL, profile.getReqId());
    } else {
      parameters.put(ProfileRequestParams.USERID, profile.getReqId());
    }
    String filePath = profile.getFieldsMap().get("imageLocation");
    if (!StringUtil.isEmpty(filePath)) {
      File file;
      try {
        file = new File(filePath);
      } catch (Exception e) {
        logger.log(Level.SEVERE, Messages.ProfileInfo_9 + "updateProfilePhoto()", e);
        throw new ProfileServiceException(e);
      }
      String name = filePath.substring(filePath.lastIndexOf('\\') + 1);

      int dot = name.lastIndexOf('.');
      String ext = null;
      if (dot > -1) {
        ext = name.substring(dot + 1); // add one for the dot!
      }
      if (StringUtil.isEmpty(ext)) {
        try {
          throw new Exception(Messages.UpdateProfileInfo_1);
        } catch (Exception e) {
          returnVal = false;
        }
      }
      Map<String, String> headers = new HashMap<String, String>();
      if (ext.equalsIgnoreCase("jpg")) {
        headers.put(
            Headers.ContentType,
            "image/jpeg"); // content-type should be image/jpeg for file extension - jpeg/jpg
      } else {
        headers.put(Headers.ContentType, "image/" + ext);
      }
      String url =
          resolveProfileUrl(
              ProfileEntity.NONADMIN.getProfileEntityType(),
              ProfileType.UPDATEPROFILEPHOTO.getProfileType());
      returnVal = executePut(url, parameters, headers, file, ClientService.FORMAT_NULL);

      profile.clearFieldsMap();
      removeProfileDataFromCache(profile.getReqId());
    }

    if (logger.isLoggable(Level.FINEST)) {
      logger.exiting(sourceClass, "updatePhoto" + returnVal);
    }
    return returnVal;
  }