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: sierra   File: MutationCommentsImporter.java   View source code 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 2
Project: rapidminer   File: AnnotationDrawUtils.java   View source code 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 3
Project: BUbiNG   File: NamedGraphServerHttpProxy.java   View source code 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 4
Project: logistimo-web-service   File: OrderExportHandler.java   View source code 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 5
Project: logistimo-web-service   File: OrderExportHandler.java   View source code 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 6
Project: Yidu   File: ReviewServiceImpl.java   View source code 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 7
Project: lams   File: GradebookService.java   View source code 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 8
Project: lams   File: PeerreviewServiceImpl.java   View source code 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 9
Project: lams   File: IMSPOXRequest.java   View source code 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 10
Project: aliyun-maxcompute-data-collectors   File: NetezzaExternalTableExportJob.java   View source code 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 11
Project: lams   File: LessonDAO.java   View source code 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 12
Project: lams   File: LessonDAO.java   View source code 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 13
Project: shop-manager   File: XssHttpServletRequestWrapper.java   View source code 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 14
Project: hadoop   File: Graph.java   View source code 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 15
Project: hadoop-oss   File: ReconfigurationServlet.java   View source code 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 16
Project: tac-kbp-eal   File: FancierDiffLogger.java   View source code 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 17
Project: airsonic   File: WikiTag.java   View source code 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 18
Project: airsonic   File: EscapeJavaScriptTag.java   View source code 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 19
Project: scanning   File: ActivemqConnectorServiceJsonMarshallingTest.java   View source code 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 20
Project: ProjectAres   File: PacketTracer.java   View source code 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 21
Project: goobi-viewer-indexer   File: MetadataHelper.java   View source code 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 22
Project: logistimo-web-service   File: MessageLogExportHandler.java   View source code 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 23
Project: logistimo-web-service   File: OrderExportHandler.java   View source code 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 24
Project: logistimo-web-service   File: OrderExportHandler.java   View source code 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 25
Project: logistimo-web-service   File: KioskExportHandler.java   View source code 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 26
Project: Android_Code_Arbiter   File: XssServlet1.java   View source code 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 27
Project: Equella   File: MetaScriptWrapper.java   View source code 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 28
Project: morf   File: MySqlDialect.java   View source code 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 29
Project: lams   File: SurveyUserDAOHibernate.java   View source code 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 30
Project: lams   File: GBUserGridRowDTO.java   View source code 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 31
Project: lams   File: GradebookService.java   View source code 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 32
Project: lams   File: AssessmentEscapeUtils.java   View source code 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 33
Project: lams   File: PeerreviewUserDAOHibernate.java   View source code 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 34
Project: lams   File: PeerreviewUserDAOHibernate.java   View source code 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 35
Project: lams   File: PeerreviewServiceImpl.java   View source code 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 36
Project: lams   File: EmailNotificationsAction.java   View source code 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 37
Project: lams   File: DacoUserDAOHibernate.java   View source code 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 38
Project: lams   File: VoteUsrAttemptDAO.java   View source code 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 39
Project: lams   File: VoteUsrAttemptDAO.java   View source code 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 40
Project: lams   File: UserDAO.java   View source code 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("%')");
    }
}
   }