Java Code Examples for org.apache.commons.lang.StringEscapeUtils

The following are top voted examples for showing how to use org.apache.commons.lang.StringEscapeUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: SurveyUserDAOHibernate.java   Source Code and License 8 votes vote down vote up
private void buildNameSearch(String searchString, StringBuilder sqlBuilder) {
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	sqlBuilder.append(" WHERE (user.first_name LIKE '%").append(escToken)
		.append("%' OR user.last_name LIKE '%").append(escToken).append("%' OR user.login_name LIKE '%")
		.append(escToken).append("%') ");
    }
}
   }
 
Example 2
Project: sierra   File: MutationCommentsImporter.java   Source Code and License 6 votes vote down vote up
private static String insertRowIntoDB(String rowLine) {
	List<String> rowFields =
		new ArrayList<String>(Arrays.asList(rowLine.split("\t")));
	Gene gene = Gene.valueOf(rowFields.remove(0));
	DrugClass drugClass = DrugClass.valueOf(rowFields.remove(0));
	int pos = Integer.parseInt(rowFields.remove(0));
	int rank = Integer.parseInt(rowFields.remove(0));
	String aas = rowFields.remove(0);
	MutType mutType = MutType.valueOf(rowFields.remove(0));
	String comment = rowFields.remove(0);
	StringBuilder statements = new StringBuilder();
	statements.append("INSERT INTO `tblCommentsWithVersions` ");
	statements.append(
		"(Gene, DrugClass, Pos, AAs, Type, " +
		"Display, Version, Date, Comment) VALUES ");
	statements.append(String.format(
		"('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
		gene, drugClass, pos, aas, mutType,
		rank, VERSION, VERSION.versionDate,
		StringEscapeUtils.escapeSql(comment.trim())));
	statements.append(';');
	return statements.toString();
}
 
Example 3
Project: rapidminer   File: AnnotationDrawUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns plain text from the editor.
 *
 * @param editor
 *            the editor from which to take the text.
 * @param onlySelected
 *            if {@code true} will only return the selected text
 * @return the text of the editor converted to plain text
 * @throws BadLocationException
 * @throws IOException
 */
public static String getPlaintextFromEditor(final JEditorPane editor, final boolean onlySelected) throws IOException,
		BadLocationException {
	if (editor == null) {
		throw new IllegalArgumentException("editor must not be null!");
	}
	HTMLDocument document = (HTMLDocument) editor.getDocument();
	StringWriter writer = new StringWriter();
	int start = 0;
	int length = document.getLength();
	if (onlySelected) {
		start = editor.getSelectionStart();
		length = editor.getSelectionEnd() - start;
	}
	editor.getEditorKit().write(writer, document, start, length);
	String text = writer.toString();
	text = AnnotationDrawUtils.removeStyleFromComment(text);
	// switch <br> and <br/> to actual newline (current system)
	text = text.replaceAll("<br.*?>", System.lineSeparator());
	// kill all other html tags
	text = text.replaceAll("\\<.*?>", "");
	text = StringEscapeUtils.unescapeHtml(text);
	return text;
}
 
Example 4
Project: BUbiNG   File: NamedGraphServerHttpProxy.java   Source Code and License 6 votes vote down vote up
public static void generate(final long hashCode, final StringBuilder content, final CharSequence[] successors, boolean notescurl) {
	content.append("<html>\n<head></head>\n<body>\n");
	// This helps in making the page text different even for the same number
	// of URLs, but not always.
	content.append("<h1>").append((char)((hashCode & 0xF) + 'A')).append((char)((hashCode >>> 4 & 0xF) + 'A')).append((char)((hashCode >>> 8 & 0xF) + 'A')).append((char)((hashCode >>> 12 & 0xF) + 'A')).append("</h1>\n");
	for (final CharSequence s : successors) {
		String ref = s.toString();
		if (!notescurl) ref = StringEscapeUtils.escapeHtml(s.toString());
		content.append("<p>Lorem ipsum dolor sit amet <a href=\""
				+ ref
				+ "\">"
				+ ref
				+ "</a>, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n");
	}
	content.append("</body>\n</html>\n");
}
 
Example 5
Project: logistimo-web-service   File: OrderExportHandler.java   Source Code and License 6 votes vote down vote up
private StringBuilder getItemSb(MaterialCatalogService mcs, DomainConfig dc, IDemandItem item)
    throws ServiceException {
  StringBuilder itemSb = new StringBuilder();

  IMaterial m = mcs.getMaterial(item.getMaterialId());
  itemSb.append(m.getMaterialId() != null ? m.getMaterialId() : CharacterConstants.EMPTY)
      .append(CharacterConstants.COMMA)
      .append(m.getCustomId() != null ? StringEscapeUtils.escapeCsv(m.getCustomId())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(StringEscapeUtils.escapeCsv(m.getName())).append(CharacterConstants.COMMA)
      .append(item.getReason() != null ? StringEscapeUtils.escapeCsv(item.getReason())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(BigUtil.getFormattedValue(item.getQuantity()));

  if (!dc.isDisableOrdersPricing()) {
    itemSb.append(CharacterConstants.COMMA)
        .append(item.getCurrency() != null ? StringEscapeUtils.escapeCsv(item.getCurrency())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(item.getFormattedPrice()).append(CharacterConstants.COMMA)
        .append(item.getDiscount()).append(CharacterConstants.COMMA)
        .append(item.computeTotalPrice(true));
  }
  return itemSb;
}
 
Example 6
Project: logistimo-web-service   File: OrderExportHandler.java   Source Code and License 6 votes vote down vote up
StringBuilder getLocationSb(DomainConfig dc, IKiosk c, Locale locale) {
  StringBuilder locationSb = new StringBuilder();
  locationSb.append(c.getCountry() != null ? StringEscapeUtils.escapeCsv(c.getCountry())
      : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(c.getState() != null ? StringEscapeUtils.escapeCsv(c.getState())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(c.getDistrict() != null ? StringEscapeUtils.escapeCsv(c.getDistrict())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(c.getTaluk() != null ? StringEscapeUtils.escapeCsv(c.getTaluk())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(c.getCity() != null ? StringEscapeUtils.escapeCsv(c.getCity())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(c.getStreet() != null ? StringEscapeUtils.escapeCsv(c.getStreet())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(c.getPinCode() != null ? StringEscapeUtils.escapeCsv(c.getPinCode())
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(order.getLatitude() != null ? order.getLatitude() : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(order.getLongitude() != null ? order.getLongitude() : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(order.getGeoAccuracy() != null ? NumberUtil.getDoubleValue(order.getGeoAccuracy()) : CharacterConstants.EMPTY)
      .append(CharacterConstants.COMMA)
      .append(order.getGeoErrorCode() != null ? StringEscapeUtils.escapeCsv(GeoUtil.getGeoErrorMessage(order.getGeoErrorCode(), locale))
          : CharacterConstants.EMPTY);
  return locationSb;
}
 
Example 7
Project: Yidu   File: ReviewServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 创建检索条件
 * 
 * @param searchBean
 *            检索条件
 * @param hql
 *            hql
 * @param params
 *            参数
 */
private void buildCondtion(ReviewSearchBean searchBean, StringBuffer hql, List<Object> params) {
    if (Utils.isDefined(searchBean.getArticleno())) {
        hql.append(" AND articleno = ? ");
        params.add(searchBean.getArticleno());
    }

    if (Utils.isDefined(searchBean.getArticlename())) {
        hql.append(" AND articlename like ? ");
        params.add("%" + StringEscapeUtils.escapeSql(searchBean.getArticlename()) + "%");
    }

    if (Utils.isDefined(searchBean.getLoginid())) {
        hql.append(" AND loginid like  ?");
        params.add("%" + StringEscapeUtils.escapeSql(searchBean.getLoginid()) + "%");
    }

    if (Utils.isDefined(searchBean.getChaptername())) {
        hql.append(" AND chaptername like  ?  ");
        params.add("%" + StringEscapeUtils.escapeSql(searchBean.getChaptername()) + "%");
    }
}
 
Example 8
Project: lams   File: GradebookService.java   Source Code and License 6 votes vote down vote up
/**
    * Returns the lesson status string which is a reference to an image
    *
    * @param learnerProgress
    * @return
    */
   private String getLessonStatusStr(LearnerProgress learnerProgress) {
String status = "-";

final String IMAGES_DIR = Configuration.get(ConfigurationKeys.SERVER_URL) + "images";
if (learnerProgress != null) {
    if (learnerProgress.isComplete()) {
	status = "<i class='fa fa-check text-success'></i>";

    } else if ((learnerProgress.getAttemptedActivities() != null)
	    && (learnerProgress.getAttemptedActivities().size() > 0)) {

	String currentActivityTitle = learnerProgress.getCurrentActivity() == null ? ""
		: StringEscapeUtils.escapeHtml(learnerProgress.getCurrentActivity().getTitle());
	status = "<i class='fa fa-cog' title='" + currentActivityTitle + "'></i>";
    }
}
return status;
   }
 
Example 9
Project: lams   File: PeerreviewServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
   public StyledCriteriaRatingDTO getUsersRatingsCommentsByCriteriaIdDTO(Long toolContentId, Long toolSessionId,
    RatingCriteria criteria, Long currentUserId, boolean skipRatings, int sorting, String searchString,
    boolean getAllUsers, boolean getByUser) {

if (skipRatings) {
    return ratingService.convertToStyledDTO(criteria, currentUserId, getAllUsers, null);
}

List<Object[]> rawData = peerreviewUserDao.getRatingsComments(toolContentId, toolSessionId, criteria,
	currentUserId, null, null, sorting, searchString, getByUser, ratingService,
	userManagementService);

for (Object[] raw : rawData) {
    raw[raw.length - 2] = (Object) StringEscapeUtils.escapeCsv((String)raw[raw.length - 2]);
}
// if !getByUser -> is get current user's ratings from other users ->
// convertToStyledJSON.getAllUsers needs to be true otherwise current user (the only one in the set!) is dropped
return ratingService.convertToStyledDTO(criteria, currentUserId, !getByUser || getAllUsers, rawData);
   }
 
Example 10
Project: lams   File: IMSPOXRequest.java   Source Code and License 6 votes vote down vote up
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
	String dataXml = "";
	if (resultData != null) {
		String format = isUrl ? resultDataUrl : resultDataText;
		dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
	}
	//*LAMS* the following line was added by LAMS and also messageIdentifier was added to the line after it
	String messageIdentifier = UUID.randomUUID().toString();
	String xml = String.format(replaceResultMessage, messageIdentifier, StringEscapeUtils.escapeXml(sourcedid),
			StringEscapeUtils.escapeXml(score), dataXml);

	HttpParameters parameters = new HttpParameters();
	String hash = getBodyHash(xml);
	parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));

	CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
	HttpPost request = new HttpPost(url);
	request.setHeader("Content-Type", "application/xml");
	request.setEntity(new StringEntity(xml, "UTF-8"));
	signer.setAdditionalParameters(parameters);
	signer.sign(request);
	return request;
}
 
Example 11
Project: aliyun-maxcompute-data-collectors   File: NetezzaExternalTableExportJob.java   Source Code and License 6 votes vote down vote up
@Override
protected void propagateOptionsToJob(Job job) {
  Configuration conf = job.getConfiguration();
  String nullValue = options.getInNullStringValue();
  if (nullValue != null) {
    conf.set(DirectNetezzaManager.NETEZZA_NULL_VALUE,
        StringEscapeUtils.unescapeJava(nullValue));
  }
  conf.setInt(DelimiterSet.INPUT_FIELD_DELIM_KEY,
      options.getInputFieldDelim());
  conf.setInt(DelimiterSet.INPUT_RECORD_DELIM_KEY,
      options.getInputRecordDelim());
  conf.setInt(DelimiterSet.INPUT_ENCLOSED_BY_KEY,
      options.getInputEnclosedBy());
  // Netezza uses \ as the escape character. Force the use of it
  int escapeChar = options.getInputEscapedBy();
  if (escapeChar > 0) {
    if (escapeChar != '\\') {
      LOG.info(
          "Setting escaped char to \\ for Netezza external table export");
    }
    conf.setInt(DelimiterSet.INPUT_ESCAPED_BY_KEY, '\\');
  }
  conf.setBoolean(DelimiterSet.INPUT_ENCLOSE_REQUIRED_KEY,
      options.isOutputEncloseRequired());
}
 
Example 12
Project: lams   File: LessonDAO.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
   @Override
   public List<User> getLearnersByLesson(Long lessonId, String searchPhrase, Integer limit, Integer offset,
    boolean orderAscending) {
StringBuilder queryTextBuilder = new StringBuilder("SELECT users ").append(LessonDAO.LOAD_LEARNERS_BY_LESSON);
if (!StringUtils.isBlank(searchPhrase)) {
    String[] tokens = searchPhrase.trim().split("\\s+");
    for (String token : tokens) {
	token = StringEscapeUtils.escapeSql(token).replace("\\", "\\\\");
	queryTextBuilder.append(" AND (users.firstName LIKE '%").append(token)
		.append("%' OR users.lastName LIKE '%").append(token).append("%' OR users.login LIKE '%")
		.append(token).append("%')");
    }
}
String order = orderAscending ? "ASC" : "DESC";
queryTextBuilder.append(" ORDER BY users.firstName ").append(order).append(", users.lastName ").append(order)
	.append(", users.login ").append(order);
Query query = getSession().createQuery(queryTextBuilder.toString()).setLong("lessonId", lessonId);
if (limit != null) {
    query.setMaxResults(limit);
}
if (offset != null) {
    query.setFirstResult(offset);
}
return query.list();
   }
 
Example 13
Project: lams   File: LessonDAO.java   Source Code and License 6 votes vote down vote up
@Override
   public Integer getCountLearnersByLesson(long lessonId, String searchPhrase) {
StringBuilder queryTextBuilder = new StringBuilder("SELECT COUNT(*) ")
	.append(LessonDAO.LOAD_LEARNERS_BY_LESSON);
if (!StringUtils.isBlank(searchPhrase)) {
    String[] tokens = searchPhrase.trim().split("\\s+");
    for (String token : tokens) {
	token = StringEscapeUtils.escapeSql(token).replace("\\", "\\\\");
	queryTextBuilder.append(" AND (users.firstName LIKE '%").append(token)
		.append("%' OR users.lastName LIKE '%").append(token).append("%' OR users.login LIKE '%")
		.append(token).append("%')");
    }
}

Query query = getSession().createQuery(queryTextBuilder.toString()).setLong("lessonId", lessonId);
Object value = query.uniqueResult();
return ((Number) value).intValue();
   }
 
Example 14
Project: shop-manager   File: XssHttpServletRequestWrapper.java   Source Code and License 5 votes vote down vote up
@Override    
public String[] getParameterValues(String name) {    
    String[] values = super.getParameterValues(name);    
    if(values != null) {    
        int length = values.length;    
        String[] escapseValues = new String[length];    
        for(int i = 0; i < length; i++){    
            escapseValues[i] = StringEscapeUtils.escapeHtml(values[i]);    
        }    
        return escapseValues;    
    }    
    return super.getParameterValues(name);    
}
 
Example 15
Project: hadoop   File: Graph.java   Source Code and License 5 votes vote down vote up
private static String wrapSafeString(String label) {
  if (label.indexOf(',') >= 0) {
    if (label.length()>14) {
      label = label.replaceAll(",", ",\n");
    }
  }
  label = "\"" + StringEscapeUtils.escapeJava(label) + "\"";
  return label;
}
 
Example 16
Project: hadoop-oss   File: ReconfigurationServlet.java   Source Code and License 5 votes vote down vote up
private void printHeader(PrintWriter out, String nodeName) {
  out.print("<html><head>");
  out.printf("<title>%s Reconfiguration Utility</title>%n",
             StringEscapeUtils.escapeHtml(nodeName));
  out.print("</head><body>\n");
  out.printf("<h1>%s Reconfiguration Utility</h1>%n",
             StringEscapeUtils.escapeHtml(nodeName));
}
 
Example 17
Project: tac-kbp-eal   File: FancierDiffLogger.java   Source Code and License 5 votes vote down vote up
private void logDocumentContext(final String originalDocText, final Response response,
    StringBuilder out) {
  out.append("<h3>Context:</h3>");
  out.append("<div>");
  out.append(StringEscapeUtils.escapeHtml(this.context(originalDocText, response)));
  out.append("</div>");
  out.append("<br>");
}
 
Example 18
Project: airsonic   File: WikiTag.java   Source Code and License 5 votes vote down vote up
public int doEndTag() throws JspException {
    String result;
    synchronized (RENDER_ENGINE) {
        result = RENDER_ENGINE.render(StringEscapeUtils.unescapeXml(text), RENDER_CONTEXT);
    }
    try {
        pageContext.getOut().print(result);
    } catch (IOException x) {
        throw new JspTagException(x);
    }
    return EVAL_PAGE;
}
 
Example 19
Project: airsonic   File: EscapeJavaScriptTag.java   Source Code and License 5 votes vote down vote up
public int doEndTag() throws JspException {
    try {
        pageContext.getOut().print(StringEscapeUtils.escapeJavaScript(string));
    } catch (IOException x) {
        throw new JspTagException(x);
    }
    return EVAL_PAGE;
}
 
Example 20
Project: scanning   File: ActivemqConnectorServiceJsonMarshallingTest.java   Source Code and License 5 votes vote down vote up
@After
	public void tearDown() throws Exception {
		if (json != null) {
			// So we can see what's going on
//			System.out.println("JSON: " + json);

			// To make it easy to replace expected JSON values in the code when we're sure they're correct
			@SuppressWarnings("unused")
			String javaLiteralForJSONString = '"' + StringEscapeUtils.escapeJava(json) + '"';
//			System.out.println("Java literal:\n" + javaLiteralForJSONString);
		}
		json = null;
		marshaller = null;
		ActivemqConnectorService.setJsonMarshaller(null);
	}
 
Example 21
Project: ProjectAres   File: PacketTracer.java   Source Code and License 5 votes vote down vote up
@Override
public PacketDataSerializer a(String s) {
    value("String", StringEscapeUtils.escapeJava(s));
    try {
        mute = true;
        return super.a(s);
    } finally {
        mute = false;
    }
}
 
Example 22
Project: goobi-viewer-indexer   File: MetadataHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param fieldValue
 * @return
 */
public static String applyValueDefaultModifications(String fieldValue) {
    String ret = fieldValue;
    if (StringUtils.isNotEmpty(ret)) {
        // Remove any prior HTML escaping, otherwise strings like '&amp;amp;' might occur
        ret = StringEscapeUtils.unescapeHtml(ret);
    }

    return ret;
}
 
Example 23
Project: logistimo-web-service   File: MessageLogExportHandler.java   Source Code and License 5 votes vote down vote up
@Override
public String toCSV(Locale locale, String timezone, DomainConfig dc, String type) {
  String str = "";
  String status = "";
  String name;
  String ph;
  try {
    UsersService as = Services.getService(UsersServiceImpl.class, locale);
    try {
      IUserAccount u = as.getUserAccount(messageLog.getUserId());
      MessageService smsService = MessageService.getInstance(MessageService.SMS, u.getCountry());
      name = u.getFullName();
      ph = u.getMobilePhoneNumber();
      status = smsService.getStatusMessage(messageLog.getStatus(), locale);
    } catch (ObjectNotFoundException e) {
      name = messageLog.getUserId() + "(" + "User deleted" + ")";
      ph = "";
    }
    str += name + ",";
    str += ph + ",";
    str +=  messageLog.getEventType() + "," + StringEscapeUtils.escapeCsv( messageLog.getMessage()) + ",";
    str += status + ",";
    str += LocalDateUtil.format(messageLog.getTimestamp(), locale, timezone);
  } catch (MessageHandlingException ignored) {
    // ignore
  }
  return str;
}
 
Example 24
Project: logistimo-web-service   File: OrderExportHandler.java   Source Code and License 5 votes vote down vote up
private StringBuilder getAccountingSb(DomainConfig dc) {
  StringBuilder accSb = null;
  if (dc.isAccountingEnabled() && !dc.isDisableOrdersPricing()) {
    accSb = new StringBuilder();
    //accSb.append(Order.getFormattedPrice(getPaid())).append(CharacterConstants.COMMA)
    accSb.append(order.getPaymentOption() != null ? order.getPaymentOption() : CharacterConstants.EMPTY)
        .append(CharacterConstants.COMMA)
        .append(order.getPaid() != null ? BigUtil.getFormattedValue(order.getPaid()) : 0).append(CharacterConstants.COMMA)
        .append(order.getPaidStatus() != null ? StringEscapeUtils.escapeCsv(order.getPaidStatus()) : CharacterConstants.EMPTY)
        .append(CharacterConstants.COMMA)
        .append(order.getPaymentHistory() != null ? StringEscapeUtils.escapeCsv(order.getPaymentHistory()) : CharacterConstants.EMPTY);
  }
  return accSb;
}
 
Example 25
Project: logistimo-web-service   File: OrderExportHandler.java   Source Code and License 5 votes vote down vote up
private StringBuilder getTagSb(DomainConfig dc) {
  StringBuilder tagSb = new StringBuilder();
  List<String> ktgs = order.getTags(TagUtil.TYPE_ENTITY);
  List<String> otgs = order.getTags(TagUtil.TYPE_ORDER);
  tagSb.append(
      ktgs != null && !ktgs.isEmpty() ? StringEscapeUtils.escapeCsv(StringUtil.getCSV(ktgs))
          : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
      .append(otgs != null && !otgs.isEmpty() ? StringEscapeUtils
          .escapeCsv(StringUtil.getCSV(otgs)) : CharacterConstants.EMPTY);

  return tagSb;
}
 
Example 26
Project: logistimo-web-service   File: KioskExportHandler.java   Source Code and License 5 votes vote down vote up
private StringBuilder constructKioskDetails(IKiosk kiosk) {
  StringBuilder ksb = new StringBuilder();
  if (kiosk != null) {
    ksb.append(kiosk.getKioskId()).append(CharacterConstants.COMMA)
        .append(kiosk.getCustomId() != null ? StringEscapeUtils.escapeCsv(kiosk.getCustomId())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(StringEscapeUtils.escapeCsv(kiosk.getName())).append(CharacterConstants.COMMA)
        .append(kiosk.getCountry() != null ? StringEscapeUtils.escapeCsv(kiosk.getCountry())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(kiosk.getState() != null ? StringEscapeUtils.escapeCsv(kiosk.getState())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(kiosk.getDistrict() != null ? StringEscapeUtils.escapeCsv(kiosk.getDistrict())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(kiosk.getTaluk() != null ? StringEscapeUtils.escapeCsv(kiosk.getTaluk())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(kiosk.getCity() != null ? StringEscapeUtils.escapeCsv(kiosk.getCity())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(kiosk.getStreet() != null ? StringEscapeUtils.escapeCsv(kiosk.getStreet())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(kiosk.getPinCode() != null ? StringEscapeUtils.escapeCsv(kiosk.getPinCode())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA)
        .append(kiosk.getLatitude()).append(CharacterConstants.COMMA)
        .append(kiosk.getLongitude()).append(CharacterConstants.COMMA)
        .append(kiosk.getGeoAccuracy()).append(CharacterConstants.COMMA)
        .append(kiosk.getGeoError() != null ? StringEscapeUtils.escapeCsv(kiosk.getGeoError())
            : CharacterConstants.EMPTY).append(CharacterConstants.COMMA);
  } else {
    ksb.append(",,,,,,,,,,,,,,");
  }
  return ksb;
}
 
Example 27
Project: Android_Code_Arbiter   File: XssServlet1.java   Source Code and License 5 votes vote down vote up
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String input1 = req.getParameter("input1");

    resp.getWriter().write(input1);

    resp.getWriter().write(ESAPI.encoder().encodeForHTML(input1));
    resp.getWriter().write(StringEscapeUtils.escapeHtml(input1));
}
 
Example 28
Project: Equella   File: ExtendedPropertiesLayout.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("nls")
private String escapeValue(Object value)
{
	String escapedValue = StringEscapeUtils.escapeJava(String.valueOf(value));
	return StringUtils.replace(escapedValue, "\\/", "/");
}
 
Example 29
Project: Equella   File: MetaScriptWrapper.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("nls")
@Override
public void add(String name, String content)
{
	StringBuilder tag = new StringBuilder();
	tag.append("<meta name=\"");
	tag.append(StringEscapeUtils.escapeHtml(name));
	tag.append("\" content=\"");
	tag.append(StringEscapeUtils.escapeHtml(content));
	tag.append("\">\n");
	render.addHeaderMarkup(tag.toString());
}
 
Example 30
Project: morf   File: MySqlDialect.java   Source Code and License 5 votes vote down vote up
/**
 * Backslashes in MySQL denote escape sequences and have to themselves be escaped.
 *
 * @see http://dev.mysql.com/doc/refman/5.0/en/string-literals.html
 * @see org.alfasoftware.morf.jdbc.SqlDialect#makeStringLiteral(java.lang.String)
 */
@Override
protected String makeStringLiteral(String literalValue) {
  if (StringUtils.isEmpty(literalValue)) {
    return "NULL";
  }
  return String.format("'%s'", StringUtils.replace(StringEscapeUtils.escapeSql(literalValue), "\\", "\\\\"));
}
 
Example 31
Project: lams   File: GBUserGridRowDTO.java   Source Code and License 5 votes vote down vote up
public GBUserGridRowDTO(User user) {
this.id = user.getUserId().toString();
this.rowName = StringEscapeUtils.escapeHtml(user.getLastName() + " " + user.getFirstName());
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.login = user.getLogin();
this.setPortraitId(user.getPortraitUuid());
   }
 
Example 32
Project: lams   File: GradebookService.java   Source Code and License 5 votes vote down vote up
/**
    * Returns the activity status string which is a reference to an image
    *
    * @param learnerProgress
    * @param activity
    * @return
    */
   private String getActivityStatusStr(LearnerProgress learnerProgress, Activity activity) {

final String IMAGES_DIR = Configuration.get(ConfigurationKeys.SERVER_URL) + "images";
if (learnerProgress != null) {
    byte statusByte = learnerProgress.getProgressState(activity);
    if (statusByte == LearnerProgress.ACTIVITY_ATTEMPTED && learnerProgress.getCurrentActivity() != null) {
	return "<i class='fa fa-cog' title='"
		+ StringEscapeUtils.escapeHtml(learnerProgress.getCurrentActivity().getTitle()) + "'></i>";
    } else if (statusByte == LearnerProgress.ACTIVITY_COMPLETED) {
	return "<i class='fa fa-check text-success'></i>";
    }
}
return "-";
   }
 
Example 33
Project: lams   File: AssessmentEscapeUtils.java   Source Code and License 5 votes vote down vote up
private static void escapeQuotesInQuestionResult(AssessmentQuestionResult questionResult) {
String answerString = questionResult.getAnswerString();
if (answerString != null) {
    String answerStringEscaped = StringEscapeUtils.escapeJavaScript(answerString);
    questionResult.setAnswerStringEscaped(answerStringEscaped);
}

AssessmentQuestion question = questionResult.getAssessmentQuestion();
String title = question.getTitle();
if (title != null) {
    String titleEscaped = StringEscapeUtils.escapeJavaScript(title);
    question.setTitleEscaped(titleEscaped);
}

for (AssessmentQuestionOption option : question.getOptions()) {
    String questionStr = option.getQuestion();
    if (questionStr != null) {
	String questionEscaped = StringEscapeUtils.escapeJavaScript(questionStr);
	option.setQuestionEscaped(questionEscaped);
    }

    String optionStr = option.getOptionString();
    if (optionStr != null) {
	String optionEscaped = StringEscapeUtils.escapeJavaScript(optionStr);
	option.setOptionStringEscaped(optionEscaped);
    }
}
   }
 
Example 34
Project: lams   File: PeerreviewUserDAOHibernate.java   Source Code and License 5 votes vote down vote up
private void buildNameSearch(String searchString, StringBuilder sqlBuilder, boolean whereDone) {
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	sqlBuilder.append(whereDone ? " AND ( " : " WHERE ( ")
		.append("user.first_name LIKE '%").append(escToken)
		.append("%' OR user.last_name LIKE '%").append(escToken).append("%' OR user.login_name LIKE '%")
		.append(escToken).append("%') ");
    }
}
   }
 
Example 35
Project: lams   File: PeerreviewUserDAOHibernate.java   Source Code and License 5 votes vote down vote up
@Override
   public List<Object[]> getPagedUsers(Long toolSessionId, Integer page, Integer size, int sorting,
    String searchString) {

String GET_USERS_FOR_SESSION = "SELECT user.uid, user.hidden, CONCAT(user.firstName, ' ', user.lastName) FROM "
	+ PeerreviewUser.class.getName() + " user WHERE user.session.sessionId = :toolSessionId ";

String sortingOrder = "";
switch (sorting) {
    case PeerreviewConstants.SORT_BY_NO:
	sortingOrder = " ORDER BY user.uid";
	break;
    case PeerreviewConstants.SORT_BY_USERNAME_ASC:
	sortingOrder = " ORDER BY user.firstName ASC";
	break;
    case PeerreviewConstants.SORT_BY_USERNAME_DESC:
	sortingOrder = " ORDER BY user.firstName DESC";
	break;
}

   	StringBuilder bldr =  new StringBuilder(GET_USERS_FOR_SESSION);
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	bldr.append(" AND ( ").append("user.firstName LIKE '%").append(escToken)
		.append("%' OR user.lastName LIKE '%").append(escToken).append("%' OR user.loginName LIKE '%")
		.append(escToken).append("%') ");
    }
}
   	bldr.append(sortingOrder);
   	
String queryString = bldr.toString();
Query query = getSession().createQuery(queryString)
	.setLong("toolSessionId", toolSessionId);
if ( page != null && size != null ) {
    query.setFirstResult(page * size).setMaxResults(size);
}
return (List<Object[]>) query.list();
   }
 
Example 36
Project: lams   File: PeerreviewServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
   public List<Object[]> getCommentsCounts(Long toolContentId, Long toolSessionId, RatingCriteria criteria,
    Integer page, Integer size, int sorting, String searchString) {

List<Object[]> rawData = peerreviewUserDao.getCommentsCounts(toolContentId, toolSessionId, criteria, page, size,
	sorting, searchString, userManagementService);

// raw data: user_id, comment_count, first_name  last_name, portrait id
for (Object[] raw : rawData) {
    raw[2] = (Object) StringEscapeUtils.escapeCsv((String)raw[2]);
}

return rawData;
   }
 
Example 37
Project: lams   File: EmailNotificationsAction.java   Source Code and License 5 votes vote down vote up
/**
    * Refreshes user list.
    */
   public ActionForward getUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException, JSONException {
Map<String, Object> map = new HashMap<String, Object>();
copySearchParametersFromRequestToMap(request, map);
Long lessonId = (Long) map.get(AttributeNames.PARAM_LESSON_ID);
Integer orgId = (Integer) map.get(AttributeNames.PARAM_ORGANISATION_ID);

if (lessonId != null) {
    if (!getSecurityService().isLessonMonitor(lessonId, getCurrentUser().getUserID(),
	    "get users for lesson email notifications", false)) {
	response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the lesson");
	return null;
    }
} else if (orgId != null) {
    if (!getSecurityService().isGroupMonitor(orgId, getCurrentUser().getUserID(),
	    "get users for course email notifications", false)) {
	response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the organisation");
	return null;
    }
}

IMonitoringService monitoringService = MonitoringServiceProxy
	.getMonitoringService(getServlet().getServletContext());

int searchType = (Integer) map.get("searchType");
Long activityId = (Long) map.get(AttributeNames.PARAM_ACTIVITY_ID);
Integer xDaystoFinish = (Integer) map.get("daysToDeadline");
String[] lessonIds = (String[]) map.get("lessonIDs");
Collection<User> users = monitoringService.getUsersByEmailNotificationSearchType(searchType, lessonId,
	lessonIds, activityId, xDaystoFinish, orgId);

JSONArray cellarray = new JSONArray();

JSONObject responcedata = new JSONObject();
responcedata.put("total", "" + users.size());
responcedata.put("page", "" + 1);
responcedata.put("records", "" + users.size());

for (User user : users) {
    JSONArray cell = new JSONArray();
    cell.put(StringEscapeUtils.escapeHtml(user.getFirstName()) + " "
	    + StringEscapeUtils.escapeHtml(user.getLastName()) + " ["
	    + StringEscapeUtils.escapeHtml(user.getLogin()) + "]");

    JSONObject cellobj = new JSONObject();
    cellobj.put("id", "" + user.getUserId());
    cellobj.put("cell", cell);
    cellarray.put(cellobj);
}
responcedata.put("rows", cellarray);
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(new String(responcedata.toString()));
return null;
   }
 
Example 38
Project: lams   File: DacoUserDAOHibernate.java   Source Code and License 5 votes vote down vote up
private void buildNameSearch(StringBuilder queryText, String searchString) {
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	queryText.append(" AND (user.first_name LIKE '%").append(escToken)
		.append("%' OR user.last_name LIKE '%").append(escToken).append("%' OR user.login_name LIKE '%")
		.append(escToken).append("%')");
    }
}
   }
 
Example 39
Project: lams   File: VoteUsrAttemptDAO.java   Source Code and License 5 votes vote down vote up
private void buildNameSearch(String searchString, StringBuilder sqlBuilder, boolean useWhere) {
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	sqlBuilder.append(useWhere ? " WHERE " : " AND ").append("(user.fullname LIKE '%").append(escToken)
		.append("%' OR user.username LIKE '%").append(escToken).append("%') ");
    }
}
   }
 
Example 40
Project: lams   File: VoteUsrAttemptDAO.java   Source Code and License 5 votes vote down vote up
private void buildCombinedSearch(String searchStringVote, String searchStringUsername, StringBuilder sqlBuilder) {

	if (!StringUtils.isBlank(searchStringVote)) {
	    String[] tokens = searchStringVote.trim().split("\\s+");
	    for (String token : tokens) {
		String escToken = StringEscapeUtils.escapeSql(token);
		sqlBuilder.append(" WHERE (userEntry LIKE '%").append(escToken).append("%') ");
	    }
	} else {
	    buildNameSearch(searchStringUsername, sqlBuilder, true);
	}
    }
 
Example 41
Project: lams   File: UserDAO.java   Source Code and License 5 votes vote down vote up
private static void addNameSearch(StringBuilder queryBuilder, String entityName, String searchPhrase) {
if (!StringUtils.isBlank(searchPhrase)) {
    String[] tokens = searchPhrase.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token).replace("\\", "\\\\");
	queryBuilder.append(" AND (").append(entityName).append(".firstName LIKE '%").append(escToken)
		.append("%' OR ").append(entityName).append(".lastName LIKE '%").append(escToken)
		.append("%' OR ").append(entityName).append(".login LIKE '%").append(escToken).append("%' OR ")
		.append(entityName).append(".email LIKE '%").append(escToken).append("%')");
    }
}
   }
 
Example 42
Project: lams   File: IMSPOXRequest.java   Source Code and License 5 votes vote down vote up
public static String getFatalResponse(String description, String message_id)
{
	Date dt = new Date();
	String messageId = ""+dt.getTime();

	return String.format(fatalMessage, 
			StringEscapeUtils.escapeXml(messageId), 
			StringEscapeUtils.escapeXml(description),
			StringEscapeUtils.escapeXml(message_id)); 
}
 
Example 43
Project: lams   File: NotebookEntryDTO.java   Source Code and License 5 votes vote down vote up
public NotebookEntryDTO(NotebookEntry entry) {
this.uid = entry.getUid();
this.entry = entry.getEntry();
if (this.entry != null) {
    this.entryEscaped = StringEscapeUtils.escapeJavaScript(this.entry);
}
this.createDate = entry.getCreateDate();
this.lastModified = (entry.getLastModified() == null) ? entry.getCreateDate() : entry.getLastModified();
   }
 
Example 44
Project: sonar-css-plugin   File: RuleDescriptionsGenerator.java   Source Code and License 5 votes vote down vote up
private String replaceLinks(String rawValidator) {
  String validator = rawValidator;
  for (Map.Entry<String, String> link : CSS_OBJECT_LINKS.entrySet()) {
    Matcher m = Pattern.compile(link.getKey()).matcher(validator);
    while (m.find()) {
      validator = m.replaceAll("<a target=\"_blank\" href=\"" + link.getValue() + "\">" + StringEscapeUtils.escapeHtml(m.group(0)) + "</a>");
    }
  }
  return validator;
}
 
Example 45
Project: lams   File: NotebookUserDAO.java   Source Code and License 5 votes vote down vote up
private void buildNameSearch(String searchString, StringBuilder sqlBuilder) {
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	sqlBuilder.append(" WHERE (user.first_name LIKE '%").append(escToken)
		.append("%' OR user.last_name LIKE '%").append(escToken).append("%' OR user.login_name LIKE '%")
		.append(escToken).append("%') ");
    }
}
   }
 
Example 46
Project: intellij-mattermost-plugin   File: MattermostClient.java   Source Code and License 5 votes vote down vote up
public Post compose(String text, String channelId) throws IOException, URISyntaxException {
    Post post = new Post();
    post.setMessage(StringEscapeUtils.escapeHtml(text));
    post.setChannelId(channelId);
    post.setUserId(this.user.getId());
    return createPost(post);
}
 
Example 47
Project: lams   File: McMonitoringAction.java   Source Code and License 5 votes vote down vote up
/**
    * Populate user jqgrid table on summary page.
    */
   public ActionForward userMasterDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {
IMcService mcService = McServiceProxy.getMcService(getServlet().getServletContext());

Long userUid = WebUtil.readLongParam(request, McAppConstants.USER_UID);
McQueUsr user = mcService.getMcUserByUID(userUid);
List<McUsrAttempt> userAttempts = mcService.getFinalizedUserAttempts(user);

// Escapes all characters that may brake JS code on assigning Java value to JS String variable (particularly
// escapes all quotes in the following way \").
if (userAttempts != null) {
    for (McUsrAttempt userAttempt : userAttempts) {
	McQueContent question = userAttempt.getMcQueContent();
	McOptsContent option = userAttempt.getMcOptionsContent();

	String questionText = question.getQuestion();
	if (questionText != null) {
	    String escapedQuestion = StringEscapeUtils.escapeJavaScript(questionText);
	    question.setEscapedQuestion(escapedQuestion);
	}

	String optionText = option.getMcQueOptionText();
	if (optionText != null) {
	    String escapedOptionText = StringEscapeUtils.escapeJavaScript(optionText);
	    option.setEscapedOptionText(escapedOptionText);
	}
    }
}

request.setAttribute(McAppConstants.ATTR_CONTENT, user.getMcSession().getMcContent());
request.setAttribute(McAppConstants.USER_ATTEMPTS, userAttempts);
request.setAttribute(McAppConstants.TOOL_SESSION_ID, user.getMcSession().getMcSessionId());
return (userAttempts == null || userAttempts.isEmpty()) ? null
	: mapping.findForward(McAppConstants.USER_MASTER_DETAIL);
   }
 
Example 48
Project: lams   File: QaMonitoringAction.java   Source Code and License 5 votes vote down vote up
/**
    * Get Paged Reflections
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   public ActionForward getReflectionsJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException, ToolException, JSONException {

Long toolSessionId = WebUtil.readLongParam(request, QaAppConstants.TOOL_SESSION_ID);

// paging parameters of tablesorter
int size = WebUtil.readIntParam(request, "size");
int page = WebUtil.readIntParam(request, "page");
Integer sortByName = WebUtil.readIntParam(request, "column[0]", true);
String searchString = request.getParameter("fcol[0]");

int sorting = QaAppConstants.SORT_BY_NO;
if (sortByName != null) {
    sorting = sortByName.equals(0) ? QaAppConstants.SORT_BY_USERNAME_ASC : QaAppConstants.SORT_BY_USERNAME_DESC;
}

//return user list according to the given sessionID
IQaService qaService = getQAService();
List<Object[]> users = qaService.getUserReflectionsForTablesorter(toolSessionId, page, size, sorting,
	searchString);

JSONArray rows = new JSONArray();
JSONObject responsedata = new JSONObject();
responsedata.put("total_rows", qaService.getCountUsersBySessionWithSearch(toolSessionId, searchString));

for (Object[] userAndReflection : users) {
    JSONObject responseRow = new JSONObject();
    responseRow.put("username", StringEscapeUtils.escapeHtml((String) userAndReflection[1]));
    if (userAndReflection.length > 2 && userAndReflection[2] != null) {
	String reflection = StringEscapeUtils.escapeHtml((String) userAndReflection[2]);
	responseRow.put(QaAppConstants.NOTEBOOK, reflection.replaceAll("\n", "<br>"));
    }
    rows.put(responseRow);
}
responsedata.put("rows", rows);
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(new String(responsedata.toString()));
return null;
   }
 
Example 49
Project: lams   File: QaUsrRespDAO.java   Source Code and License 5 votes vote down vote up
private String buildNameSearch(String searchString, String userRef) {
String filteredSearchString = null;
if (!StringUtils.isBlank(searchString)) {
    StringBuilder searchStringBuilder = new StringBuilder("");
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	searchStringBuilder.append(" AND (" + userRef + ".fullname LIKE '%").append(escToken)
		.append("%' OR " + userRef + ".username LIKE '%").append(escToken).append("%') ");
    }
    filteredSearchString = searchStringBuilder.toString();
}
return filteredSearchString;
   }
 
Example 50
Project: lams   File: QaQueUsrDAO.java   Source Code and License 5 votes vote down vote up
private void buildNameSearch(StringBuilder queryText, String searchString) {
String filteredSearchString = null;
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	queryText.append(" WHERE (fullname LIKE '%").append(escToken).append("%' OR username LIKE '%")
		.append(escToken).append("%') ");
    }
}
   }
 
Example 51
Project: lams   File: MonitoringAction.java   Source Code and License 5 votes vote down vote up
private ActionForward itemSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {

initializeScratchieService();
String sessionMapID = request.getParameter(ScratchieConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapID);
request.setAttribute(ScratchieConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());

Long itemUid = WebUtil.readLongParam(request, ScratchieConstants.ATTR_ITEM_UID);
if (itemUid.equals(-1)) {
    return null;
}
ScratchieItem item = service.getScratchieItemByUid(itemUid);
request.setAttribute(ScratchieConstants.ATTR_ITEM, item);

Long contentId = (Long) sessionMap.get(ScratchieConstants.ATTR_TOOL_CONTENT_ID);
List<GroupSummary> summaryList = service.getQuestionSummary(contentId, itemUid);

// escape JS sensitive characters in answer descriptions
for (GroupSummary summary : summaryList) {
    for (ScratchieAnswer answer : summary.getAnswers()) {
	String description = (answer.getDescription() == null) ? ""
		: StringEscapeUtils.escapeJavaScript(answer.getDescription());
	answer.setDescription(description);
    }
}

request.setAttribute(ScratchieConstants.ATTR_SUMMARY_LIST, summaryList);
return mapping.findForward(ScratchieConstants.SUCCESS);
   }
 
Example 52
Project: lams   File: ScratchieServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
   public List<ReflectDTO> getReflectionList(Long contentId) {
ArrayList<ReflectDTO> reflections = new ArrayList<>();

// get all available leaders associated with this content as only leaders have reflections
List<ScratchieSession> sessionList = scratchieSessionDao.getByContentId(contentId);
for (ScratchieSession session : sessionList) {

    ScratchieUser leader = session.getGroupLeader();
    if (leader != null) {
	NotebookEntry notebookEntry = getEntry(session.getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL,
		ScratchieConstants.TOOL_SIGNATURE, leader.getUserId().intValue());
	if ((notebookEntry != null) && StringUtils.isNotBlank(notebookEntry.getEntry())) {
	    User user = new User();
	    user.setLastName(leader.getLastName());
	    user.setFirstName(leader.getFirstName());
	    ReflectDTO reflectDTO = new ReflectDTO(user);
	    reflectDTO.setGroupName(session.getSessionName());
	    String reflection = notebookEntry.getEntry();
	    reflection = StringEscapeUtils.escapeJavaScript(reflection);
	    reflectDTO.setReflection(reflection);
	    reflectDTO.setIsGroupLeader(session.isUserGroupLeader(leader.getUid()));

	    reflections.add(reflectDTO);
	}
    }
}

return reflections;
   }
 
Example 53
Project: lams   File: LamsSecurityUtil.java   Source Code and License 5 votes vote down vote up
/**
    * Takes care about blank values. Besides, escapes CSV sensitive symbols (commas, quotes, etc) and then encodes it to be sent as a URL parameter.
    * 
    * @param value
    * @param CSV
    * @return
    * @throws UnsupportedEncodingException
    */
   private static String escapeValue(String value) throws UnsupportedEncodingException {
final String DUMMY_VALUE = "-";

String notBlankValue = StringUtils.isBlank(value) ? DUMMY_VALUE : value;
String escapedCsv = StringEscapeUtils.escapeCsv(notBlankValue);
String encodedValue = URLEncoder.encode(escapedCsv, "utf8");

return encodedValue;
   }
 
Example 54
Project: lams   File: SubmitUserDAO.java   Source Code and License 5 votes vote down vote up
private void buildNameSearch(String searchString, StringBuilder sqlBuilder) {
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	sqlBuilder.append(" AND (user.first_name LIKE '%").append(escToken)
		.append("%' OR user.last_name LIKE '%").append(escToken).append("%' OR user.login_name LIKE '%")
		.append(escToken).append("%') ");
    }
}
   }
 
Example 55
Project: lams   File: SpreadsheetUserDAOHibernate.java   Source Code and License 5 votes vote down vote up
private void buildNameSearch(String searchString, StringBuilder sqlBuilder) {
if (!StringUtils.isBlank(searchString)) {
    String[] tokens = searchString.trim().split("\\s+");
    for (String token : tokens) {
	String escToken = StringEscapeUtils.escapeSql(token);
	sqlBuilder.append(" WHERE (user.first_name LIKE '%").append(escToken)
		.append("%' OR user.last_name LIKE '%").append(escToken).append("%' OR user.login_name LIKE '%")
		.append(escToken).append("%') ");
    }
}
   }
 
Example 56
Project: hadoop   File: ReconfigurationServlet.java   Source Code and License 4 votes vote down vote up
/**
 * Print configuration options that can be changed.
 */
private void printConf(PrintWriter out, Reconfigurable reconf) {
  Configuration oldConf = reconf.getConf();
  Configuration newConf = new Configuration();

  Collection<ReconfigurationUtil.PropertyChange> changes = 
    ReconfigurationUtil.getChangedProperties(newConf, 
                                             oldConf);

  boolean changeOK = true;
  
  out.println("<form action=\"\" method=\"post\">");
  out.println("<table border=\"1\">");
  out.println("<tr><th>Property</th><th>Old value</th>");
  out.println("<th>New value </th><th></th></tr>");
  for (ReconfigurationUtil.PropertyChange c: changes) {
    out.print("<tr><td>");
    if (!reconf.isPropertyReconfigurable(c.prop)) {
      out.print("<font color=\"red\">" + 
                StringEscapeUtils.escapeHtml(c.prop) + "</font>");
      changeOK = false;
    } else {
      out.print(StringEscapeUtils.escapeHtml(c.prop));
      out.print("<input type=\"hidden\" name=\"" +
                StringEscapeUtils.escapeHtml(c.prop) + "\" value=\"" +
                StringEscapeUtils.escapeHtml(c.newVal) + "\"/>");
    }
    out.print("</td><td>" +
              (c.oldVal == null ? "<it>default</it>" : 
               StringEscapeUtils.escapeHtml(c.oldVal)) +
              "</td><td>" +
              (c.newVal == null ? "<it>default</it>" : 
               StringEscapeUtils.escapeHtml(c.newVal)) +
              "</td>");
    out.print("</tr>\n");
  }
  out.println("</table>");
  if (!changeOK) {
    out.println("<p><font color=\"red\">WARNING: properties marked red" +
                " will not be changed until the next restart.</font></p>");
  }
  out.println("<input type=\"submit\" value=\"Apply\" />");
  out.println("</form>");
}
 
Example 57
Project: shop-manager   File: XssHttpServletRequestWrapper.java   Source Code and License 4 votes vote down vote up
@Override    
public String getHeader(String name) {    
    return StringEscapeUtils.escapeHtml(super.getHeader(name));    
}
 
Example 58
Project: shop-manager   File: XssHttpServletRequestWrapper.java   Source Code and License 4 votes vote down vote up
@Override    
public String getQueryString() {    
    return StringEscapeUtils.escapeHtml(super.getQueryString());    
}
 
Example 59
Project: shop-manager   File: XssHttpServletRequestWrapper.java   Source Code and License 4 votes vote down vote up
@Override    
public String getParameter(String name) {    
    return StringEscapeUtils.escapeHtml(super.getParameter(name));    
}
 
Example 60
Project: hadoop-oss   File: ReconfigurationServlet.java   Source Code and License 4 votes vote down vote up
/**
 * Print configuration options that can be changed.
 */
private void printConf(PrintWriter out, Reconfigurable reconf) {
  Configuration oldConf = reconf.getConf();
  Configuration newConf = new Configuration();

  Collection<ReconfigurationUtil.PropertyChange> changes = 
    ReconfigurationUtil.getChangedProperties(newConf, 
                                             oldConf);

  boolean changeOK = true;
  
  out.println("<form action=\"\" method=\"post\">");
  out.println("<table border=\"1\">");
  out.println("<tr><th>Property</th><th>Old value</th>");
  out.println("<th>New value </th><th></th></tr>");
  for (ReconfigurationUtil.PropertyChange c: changes) {
    out.print("<tr><td>");
    if (!reconf.isPropertyReconfigurable(c.prop)) {
      out.print("<font color=\"red\">" + 
                StringEscapeUtils.escapeHtml(c.prop) + "</font>");
      changeOK = false;
    } else {
      out.print(StringEscapeUtils.escapeHtml(c.prop));
      out.print("<input type=\"hidden\" name=\"" +
                StringEscapeUtils.escapeHtml(c.prop) + "\" value=\"" +
                StringEscapeUtils.escapeHtml(c.newVal) + "\"/>");
    }
    out.print("</td><td>" +
              (c.oldVal == null ? "<it>default</it>" : 
               StringEscapeUtils.escapeHtml(c.oldVal)) +
              "</td><td>" +
              (c.newVal == null ? "<it>default</it>" : 
               StringEscapeUtils.escapeHtml(c.newVal)) +
              "</td>");
    out.print("</tr>\n");
  }
  out.println("</table>");
  if (!changeOK) {
    out.println("<p><font color=\"red\">WARNING: properties marked red" +
                " will not be changed until the next restart.</font></p>");
  }
  out.println("<input type=\"submit\" value=\"Apply\" />");
  out.println("</form>");
}