Java Code Examples for org.apache.commons.lang3.StringEscapeUtils#escapeJson()

The following examples show how to use org.apache.commons.lang3.StringEscapeUtils#escapeJson() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSlackProcessor.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
@Override
public void process(K key, V value) {
    try {

        String v;

        if (!StringUtils.isBlank(template)) {
            v = TemplateUtils.getInstance().process(template, getMsg(value));
            v = "{\"text\":\"" + StringEscapeUtils.escapeJson(v) + "\"}";
        } else
            v = "{\"text\":\"" + StringEscapeUtils.escapeJson(buildMsg(value)) + "\"}";

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(uri);

        StringEntity entity = new StringEntity(v);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        CloseableHttpResponse response = client.execute(httpPost);
        client.close();

        int code = response.getStatusLine().getStatusCode();
        String reason = response.getStatusLine().getReasonPhrase();

        if (code == 200)
            log.debug("Message sended to Slack key {} value {}", key, value);
        else
            log.error("Error during Slack calls: code {} reason {}", code, reason);

    } catch (Exception ex) {
        log.error("Exception during Slack calls {}", ex.getMessage());
    }
}
 
Example 2
Source File: InternalConfigStateController.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Handle request.
 *
 * @param request the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(
        final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {

    final Map<String, Object> list = getBeans(this.applicationContext);
    LOGGER.debug("Found [{}] beans to report", list.size());

    final JsonSerializer<Object> serializer = new BeanObjectJsonSerializer();
    final StringBuilder builder = new StringBuilder();
    builder.append('[');

    final Set<Map.Entry<String, Object>> entries = list.entrySet();
    final Iterator<Map.Entry<String, Object>> it = entries.iterator();

    while (it.hasNext()) {
        final Map.Entry<String, Object> entry = it.next();
        final Object obj = entry.getValue();

        final StringWriter writer = new StringWriter();
        writer.append('{');
        writer.append('\"' + entry.getKey() + "\":");
        serializer.toJson(writer, obj);
        writer.append('}');
        builder.append(writer);

        if (it.hasNext()) {
            builder.append(',');
        }
    }
    builder.append(']');
    final ModelAndView mv = new ModelAndView(VIEW_CONFIG);
    final String jsonData = StringEscapeUtils.escapeJson(builder.toString());

    mv.addObject("jsonData", jsonData);
    mv.addObject("properties", casProperties.entrySet());
    return mv;
}
 
Example 3
Source File: JsonBuilder.java    From crushpaper with GNU Affero General Public License v3.0 5 votes vote down vote up
/** Returns the value JSON encoded and quoted. */
static String quote(String value) {
	if (value == null) {
		return "null";
	}

	return "\"" + StringEscapeUtils.escapeJson(value) + "\"";
}
 
Example 4
Source File: DiscordClient.java    From Discord4J with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sends a message to the specified channel.
 *
 * @param content   The actual message to send
 * @param channelID The channel to send the message to
 * @return The message that was sent.
 * @throws IOException
 * @throws ParseException
 */
public Message sendMessage(String content, String channelID) throws IOException, ParseException {
    if (null != ws) {

        content = StringEscapeUtils.escapeJson(content);
        
        try {
            String response = Requests.POST.makeRequest(DiscordEndpoints.CHANNELS + channelID + "/messages",
                    new StringEntity("{\"content\":\"" + content + "\",\"mentions\":[]}","UTF-8"),
                    new BasicNameValuePair("authorization", token),
                    new BasicNameValuePair("content-type", "application/json"));


            JSONObject object1 = (JSONObject) JSON_PARSER.parse(response);
            String time = (String) object1.get("timestamp");
            String messageID = (String) object1.get("id");

            Channel channel = getChannelByID(channelID);
            Message message = new Message(messageID, content, this.ourUser, channel, this.convertFromTimestamp(time));
            channel.addMessage(message); //Had to be moved here so that if a message is edited before the MESSAGE_CREATE event, it doesn't error
            DiscordClient.this.dispatcher.dispatch(new MessageSendEvent(message));
        return message;
        } catch (HTTP403Exception e) {
            Discord4J.logger.error("Received 403 error attempting to send message; is your login correct?");
            return null;
        }

    } else {
        Discord4J.logger.error("Bot has not signed in yet!");
        return null;
    }
}
 
Example 5
Source File: DiscordClient.java    From Discord4J with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Edits a specified message. Currently, Discord only allows you to edit your own message
 * 
 * @param content   The new content of the message
 * @param messageID The id of the message to edit
 * @param channelID The channel the message exists in
 * @throws ParseException
 */
public void editMessage(String content, String messageID, String channelID) throws ParseException {
    if (null != ws) {

        content = StringEscapeUtils.escapeJson(content);
        
        Channel channel = getChannelByID(channelID);
        if (channel == null) {
            Discord4J.logger.error("Channel id " +  channelID + " doesn't exist!");
            return;
        }
        
        Message oldMessage = channel.getMessageByID(messageID);
        
        try {
            String response = Requests.PATCH.makeRequest(DiscordEndpoints.CHANNELS + channelID + "/messages/" + messageID, 
                    new StringEntity("{\"content\":\"" + content + "\", \"mentions\":[]}", "UTF-8"), 
                    new BasicNameValuePair("authorization", token),
                    new BasicNameValuePair("content-type", "application/json"));

            JSONObject object1 = (JSONObject) JSON_PARSER.parse(response);

            Message newMessage = new Message((String) object1.get("id"), content, this.ourUser, getChannelByID(channelID), 
                    oldMessage.getTimestamp());
            //Event dispatched here because otherwise there'll be an NPE as for some reason when the bot edits a message,
            // the event chain goes like this:
            //Original message edited to null, then the null message edited to the new content
            DiscordClient.this.dispatcher.dispatch(new MessageUpdateEvent(oldMessage, newMessage));
            oldMessage.setContent(content);
        } catch (HTTP403Exception e) {
            Discord4J.logger.error("Received 403 error attempting to send message; is your login correct?");
        }

    } else {
        Discord4J.logger.error("Bot has not signed in yet!");
    }
}
 
Example 6
Source File: ActErrorPageRender.java    From actframework with Apache License 2.0 5 votes vote down vote up
private String jsonContent(ErrorResult error, Integer errorCode, String errorMsg) {
    Object payload = error.attachment();
    if (null != payload) {
        return com.alibaba.fastjson.JSON.toJSONString(payload);
    }
    errorMsg = StringEscapeUtils.escapeJson(errorMsg);
    if (null == errorCode) {
        return S.concat("{\"ts\":", $.ms(),  ",\"message\":\"", errorMsg, "\"}");
    } else {
        return S.concat("{\"ts\":", $.ms(), ",\"code\":", S.string(errorCode), ",\"message\":\"", errorMsg, "\"}");
    }
}
 
Example 7
Source File: HDFSTool.java    From systemds with Apache License 2.0 4 votes vote down vote up
public static String metaDataToString(ValueType vt, ValueType[] schema, DataType dt, DataCharacteristics dc,
		OutputInfo outinfo, FileFormatProperties formatProperties) throws JSONException, DMLRuntimeException
{
	OrderedJSONObject mtd = new OrderedJSONObject(); // maintain order in output file

	//handle data type and value types (incl schema for frames)
	mtd.put(DataExpression.DATATYPEPARAM, dt.toString().toLowerCase());
	if (schema == null) {
		mtd.put(DataExpression.VALUETYPEPARAM, vt.toExternalString().toLowerCase());
	}	
	else {
		StringBuffer schemaSB = new StringBuffer();
		for(int i=0; i < schema.length; i++) {
			if( schema[i] == ValueType.UNKNOWN )
				schemaSB.append("*");
			else
				schemaSB.append(schema[i].toString());
			schemaSB.append(DataExpression.DEFAULT_DELIM_DELIMITER);
		}
		mtd.put(DataExpression.SCHEMAPARAM, schemaSB.toString());
	}
	
	//handle output dimensions
	if( !dt.isScalar() ) {
		mtd.put(DataExpression.READROWPARAM, dc.getRows());
		mtd.put(DataExpression.READCOLPARAM, dc.getCols());
		// handle output nnz and binary block configuration
		if( dt.isMatrix() ) {
			if (outinfo == OutputInfo.BinaryBlockOutputInfo ) {
				mtd.put(DataExpression.ROWBLOCKCOUNTPARAM, dc.getBlocksize());
				mtd.put(DataExpression.COLUMNBLOCKCOUNTPARAM, dc.getBlocksize());
			}
			mtd.put(DataExpression.READNNZPARAM, dc.getNonZeros());
		}
	}
		
	//handle format type and additional arguments	
	mtd.put(DataExpression.FORMAT_TYPE, OutputInfo.outputInfoToStringExternal(outinfo));
	
	if (formatProperties != null) {
		String description = formatProperties.getDescription();
		if (StringUtils.isNotEmpty(description)) {
			String jsonDescription = StringEscapeUtils.escapeJson(description);
			mtd.put(DataExpression.DESCRIPTIONPARAM, jsonDescription);
		}
	}

	String userName = System.getProperty("user.name");
	if (StringUtils.isNotEmpty(userName)) {
		mtd.put(DataExpression.AUTHORPARAM, userName);
	} else {
		mtd.put(DataExpression.AUTHORPARAM, "SystemDS");
	}

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
	mtd.put(DataExpression.CREATEDPARAM, sdf.format(new Date()));

	return mtd.toString(4); // indent with 4 spaces	
}
 
Example 8
Source File: PromWriter.java    From sofa-lookout with Apache License 2.0 4 votes vote down vote up
private String formatString(String str) {
    return StringEscapeUtils.escapeJson(str);
}
 
Example 9
Source File: Servlets.java    From atlas with Apache License 2.0 4 votes vote down vote up
public static String escapeJsonString(String inputStr) {
    ParamChecker.notNull(inputStr, "Input String cannot be null");
    return StringEscapeUtils.escapeJson(inputStr);
}
 
Example 10
Source File: ProfileWrapper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public String getPlanText() {
  return StringEscapeUtils.escapeJson(profile.getPlan());
}
 
Example 11
Source File: Servlets.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
public static String escapeJsonString(String inputStr) {
    ParamChecker.notNull(inputStr, "Input String cannot be null");
    return StringEscapeUtils.escapeJson(inputStr);
}
 
Example 12
Source File: WebHookNotifier.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private String escapeValue(String value, String contentType) {
  if (APPLICATION_JSON.equals(contentType)) {
    return StringEscapeUtils.escapeJson(value);
  }
  return value;
}
 
Example 13
Source File: HDFSTool.java    From systemds with Apache License 2.0 4 votes vote down vote up
public static String metaDataToString(ValueType vt, ValueType[] schema, DataType dt, DataCharacteristics dc,
		FileFormat fmt, FileFormatProperties formatProperties, PrivacyConstraint privacyConstraint) throws JSONException, DMLRuntimeException
{
	OrderedJSONObject mtd = new OrderedJSONObject(); // maintain order in output file

	//handle data type and value types (incl schema for frames)
	mtd.put(DataExpression.DATATYPEPARAM, dt.toString().toLowerCase());
	if (schema == null) {
		mtd.put(DataExpression.VALUETYPEPARAM, vt.toExternalString().toLowerCase());
	}	
	else {
		StringBuffer schemaSB = new StringBuffer();
		for(int i=0; i < schema.length; i++) {
			if( schema[i] == ValueType.UNKNOWN )
				schemaSB.append("*");
			else
				schemaSB.append(schema[i].toString());
			schemaSB.append(DataExpression.DEFAULT_DELIM_DELIMITER);
		}
		mtd.put(DataExpression.SCHEMAPARAM, schemaSB.toString());
	}
	
	//handle output dimensions
	if( !dt.isScalar() ) {
		mtd.put(DataExpression.READROWPARAM, dc.getRows());
		mtd.put(DataExpression.READCOLPARAM, dc.getCols());
		// handle output nnz and binary block configuration
		if( dt.isMatrix() ) {
			if (fmt == FileFormat.BINARY) {
				mtd.put(DataExpression.ROWBLOCKCOUNTPARAM, dc.getBlocksize());
				mtd.put(DataExpression.COLUMNBLOCKCOUNTPARAM, dc.getBlocksize());
			}
			mtd.put(DataExpression.READNNZPARAM, dc.getNonZeros());
		}
	}
		
	//handle format type and additional arguments
	mtd.put(DataExpression.FORMAT_TYPE, fmt.toString());
	
	if (formatProperties != null) {
		String description = formatProperties.getDescription();
		if (StringUtils.isNotEmpty(description)) {
			String jsonDescription = StringEscapeUtils.escapeJson(description);
			mtd.put(DataExpression.DESCRIPTIONPARAM, jsonDescription);
		}
	}

	//add privacy constraints
	if ( privacyConstraint != null ){
		mtd.put(DataExpression.PRIVACY, privacyConstraint.getPrivacyLevel().name());
	}

	//add username and time
	String userName = System.getProperty("user.name");
	if (StringUtils.isNotEmpty(userName)) {
		mtd.put(DataExpression.AUTHORPARAM, userName);
	} else {
		mtd.put(DataExpression.AUTHORPARAM, "SystemDS");
	}

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
	mtd.put(DataExpression.CREATEDPARAM, sdf.format(new Date()));

	return mtd.toString(4); // indent with 4 spaces	
}
 
Example 14
Source File: EscapeJsonFilter.java    From jinjava with Apache License 2.0 4 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  return StringEscapeUtils.escapeJson(Objects.toString(var));
}
 
Example 15
Source File: MeasurementUtil.java    From sofa-lookout with Apache License 2.0 2 votes vote down vote up
/**
 * 非数值或者String类型的对象进行,Json化处理(包括转义);
 *
 * @param value
 * @param <T>
 * @return
 */
public static <T> Object printValue(T value) {
    return value == null ? value : (value instanceof String || value instanceof Number ? value
        : StringEscapeUtils.escapeJson(JSON.toJSONString(value)));
}
 
Example 16
Source File: ChartJsonBuilder.java    From core with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Adds a row element with a string value. The string value is quoted.
 * 
 * @param value
 *            The value of the element to be added to the row
 */
public void addRowElement(String value) {
	String escapedValue = StringEscapeUtils.escapeJson(value);
	String rowElement = "{\"v\": \"" + escapedValue + "\"}";
	rowElementsList.add(rowElement);
}