Example usage for org.apache.commons.lang3 StringEscapeUtils unescapeXml

List of usage examples for org.apache.commons.lang3 StringEscapeUtils unescapeXml

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils unescapeXml.

Prototype

public static final String unescapeXml(final String input) 

Source Link

Document

Unescapes a string containing XML entity escapes to a string containing the actual Unicode characters corresponding to the escapes.

Supports only the five basic XML entities (gt, lt, quot, amp, apos).

Usage

From source file:com.foo.manager.commonManager.thread.HttpHandleThread.java

private String handleXml_sn_cancelNotify(String jsonString) throws CommonException {

    // String jsonReturnString = "";
    SimpleDateFormat sf = CommonUtil.getDateFormatter(CommonDefine.COMMON_FORMAT_1);

    System.out.println("---------------------------?FPAPI_SN_cancelNotify-------------------------------");
    // /*from w  w w .  ja va 2  s .c  o m*/
    JSONObject jsonObject = JSONObject.fromObject(jsonString);

    JSONObject orderInfo = (JSONObject) jsonObject.get("orderInfo");

    // ??
    ResourceBundle bundle = CommonUtil.getMessageMappingResource("CEB_SN");

    JSONObject result = new JSONObject();

    String orderCode = orderInfo.get("orderCode") != null ? orderInfo.get("orderCode").toString() : "";
    String orderType = orderInfo.get("orderType") != null ? orderInfo.get("orderType").toString() : "";

    if ("201".equals(orderType)) {
        //t_sn_order?ORDER_CODE = orderCode
        List orderList = commonManagerMapper.selectTableListByCol("T_SN_ORDER_DETAIL", "ORDER_CODE", orderCode,
                null, null);

        Map orderDetailSearch = orderList.size() > 0 ? (Map) orderList.get(0) : null;

        //?
        if (orderDetailSearch == null) {
            //?false
            result.put("success", "false");
            result.put("errorCode", "");
            result.put("errorMsg", "");
        } else {
            String orderStatus = orderDetailSearch.get("ORDER_STATUS") != null
                    ? orderDetailSearch.get("ORDER_STATUS").toString()
                    : "";

            if ("2".equals(orderStatus)) {
                //ORDER_STATUS = 2True
                result.put("success", "true");
                result.put("errorCode", "");
                result.put("errorMsg", "");
            } else if ("1".equals(orderStatus)) {
                //ORDER_STATUS = 1false
                result.put("success", "false");
                result.put("errorCode", "");
                result.put("errorMsg", "");
            } else if ("0".equals(orderStatus)) {
                //ORDER_STATUS = 0??????,OKTrue?OK,ORDER_STATUS1false
                Map orderSearch = commonManagerMapper.selectTableById("T_SN_ORDER", "ORDER_ID",
                        Integer.valueOf(orderDetailSearch.get("ORDER_ID").toString()));

                Map order = new HashMap();

                List<Map> orderItemListForCJ = new ArrayList<Map>();

                order.put("ORDER_CODE", orderSearch.get("BOL"));
                order.put("ORDER_TYPE", orderType);
                order.put("CUST", CommonUtil.getSystemConfigProperty("CJ_cust"));

                String xmlStringData = XmlUtil.generalCommonXml_CJ("DATA", order, orderItemListForCJ);

                String requestXmlData = XmlUtil.generalSoapXml_CJ(xmlStringData, "sendCancelStockOrder");

                //System.out.println(requestXmlData);
                //??????
                String response = HttpUtil.sendHttpCMD_CJ(requestXmlData,
                        CommonUtil.getSystemConfigProperty("CJ_sendCancel_requestUrl").toString());

                //??
                //               String returnXmlData = XmlUtil
                //                     .getResponseFromXmlString_CJ(response);

                String returnXmlData = XmlUtil.getTotalMidValue(StringEscapeUtils.unescapeXml(response),
                        "<ns:return>", "</ns:return>");

                //?
                //
                Map orderResult = XmlUtil.parseXmlFPAPI_SingleNodes(returnXmlData, "//DATA/ORDER/child::*");

                //
                if (orderResult.containsKey("CD") && "OK".equals(orderResult.get("CD").toString())) {
                    //ORDER_STATUS2
                    List<String> colNames = new ArrayList<String>();
                    List<Object> colValues = new ArrayList<Object>();
                    colNames.add("ORDER_STATUS");
                    colValues.add("2");
                    commonManagerMapper.updateTableByNVList("t_sn_order", "BOL", orderCode, colNames,
                            colValues);
                    //??
                    result.put("success", "true");
                    result.put("errorCode", "");
                    result.put("errorMsg", "");
                } else {
                    //ORDER_STATUS1
                    List<String> colNames = new ArrayList<String>();
                    List<Object> colValues = new ArrayList<Object>();
                    colNames.add("ORDER_STATUS");
                    colValues.add("1");
                    commonManagerMapper.updateTableByNVList("t_sn_order", "BOL", orderCode, colNames,
                            colValues);
                    //
                    result.put("success", "false");
                    result.put("errorCode", "");
                    result.put("errorMsg", orderResult.get("INFO"));
                }

            }

        }
    } else if ("501".equals(orderType)) {

    } else if ("601".equals(orderType)) {

    } else if ("901".equals(orderType)) {

    } else {
        //??
        result.put("success", "false");
        result.put("errorCode", "");
        result.put("errorMsg", "");
    }

    result.put("orderCode", orderCode);

    return result.toString();
}

From source file:net.subclient.subsonic.SubsonicConnection.java

/**
 * Casts an InputStream returned by method {@link #connect(ApiMethod, List) connect} to a valid SubsonicResponse
 * @param in InputStream corresponding to a previous {@link #connect(ApiMethod, List) connect} call
 * @param responseClass Type of the class that extends from SubsonicResponse and has to be returned
 * @return An object extending SubsonicResponse that results from mapping the returned JSON object into a Java object
 * @throws IOException //from  www .  j a v a2 s. com
 * @throws SubsonicException If a Subsonic error occurs
 * @throws InvalidResponseException 
 */
private <T extends SubsonicResponse> T parseResponse(InputStream in, Class<T> responseClass)
        throws IOException, SubsonicException, InvalidResponseException {
    T response = null;

    //Parse Subsonic response to String
    StringBuilder resp = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String singleLine;
    while ((singleLine = reader.readLine()) != null)
        resp.append(singleLine);
    JsonElement responseElement = this.parser.parse(StringEscapeUtils.unescapeXml(resp.toString()))
            .getAsJsonObject().get(SUBSONIC_RESPONSE_IDENTIFIER);

    // Parse Subsonic string response to its corresponding Java Object and check if an error occured
    try {
        response = this.gson.fromJson(responseElement, responseClass);
    } catch (JsonSyntaxException e) {
        throw new InvalidResponseException(e);
    }
    if (response.getStatus().equalsIgnoreCase(SubsonicResponse.STATUS_FAILED)) {
        int code = responseElement.getAsJsonObject().get("error").getAsJsonObject().get("code").getAsInt();
        String message = responseElement.getAsJsonObject().get("error").getAsJsonObject().get("message")
                .getAsString();
        throw new SubsonicException(code, message);
    }
    // Close connection input after finishing reading it
    in.close();

    // Return  mapped response
    return response;
}

From source file:net.xby1993.common.util.io.EncodeUtil.java

/**
 * Xml?XML??.//from w  ww  .j av  a 2  s  . c om
 * 
 *  &quot;bread&quot; &amp; &quot;butter&quot; "bread" & "butter"
 */
public static String unescapeXml(String xml) {
    return StringEscapeUtils.unescapeXml(xml);
}

From source file:org.ambraproject.rhino.service.taxonomy.impl.TaxonomyClassificationServiceImpl.java

/**
 * @inheritDoc/*from   www .ja  v a 2s .c o  m*/
 */
@Override
public List<String> getRawTerms(Document articleXml, Article article, boolean isTextRequired) {
    RuntimeConfiguration.TaxonomyConfiguration configuration = getTaxonomyConfiguration();

    String toCategorize = getCategorizationContent(articleXml);

    ArticleIngestion latest = articleCrudService.readLatestRevision(article).getIngestion();
    String header = String.format(MESSAGE_HEADER,
            new SimpleDateFormat("yyyy-MM-dd").format(latest.getPublicationDate()),
            latest.getJournal().getTitle(), latest.getArticleType(), article.getDoi());

    String aiMessage = String.format(MESSAGE_BEGIN, configuration.getThesaurus())
            + StringEscapeUtils.escapeXml10(String.format(MESSAGE_DOC_ELEMENT, header, toCategorize))
            + MESSAGE_END;

    HttpPost post = new HttpPost(configuration.getServer().toString());
    post.setEntity(new StringEntity(aiMessage, APPLICATION_XML_UTF_8));

    DocumentBuilder documentBuilder = newDocumentBuilder();

    Document response;
    try (CloseableHttpResponse httpResponse = httpClient.execute(post);
            InputStream stream = httpResponse.getEntity().getContent()) {
        response = documentBuilder.parse(stream);
    } catch (IOException e) {
        throw new TaxonomyRemoteServiceNotAvailableException(e);
    } catch (SAXException e) {
        throw new TaxonomyRemoteServiceInvalidBehaviorException(
                "Invalid XML returned from " + configuration.getServer(), e);
    }

    //parse result
    NodeList vectorElements = response.getElementsByTagName("VectorElement");
    List<String> results = new ArrayList<>(vectorElements.getLength());

    // Add the text that is sent to taxonomy server if isTextRequired is true
    if (isTextRequired) {
        toCategorize = StringEscapeUtils.unescapeXml(toCategorize);
        results.add(toCategorize);
    }

    //The first and last elements of the vector response are just MAITERMS
    for (int i = 1; i < vectorElements.getLength() - 1; i++) {
        results.add(vectorElements.item(i).getTextContent());
    }

    if ((isTextRequired && results.size() == 1) || results.isEmpty()) {
        log.error("Taxonomy server returned 0 terms. " + article.getDoi());
    }

    return results;
}

From source file:org.apache.jmeter.protocol.http.parser.URLCollection.java

/**
 * Convenience method for adding URLs to the collection. If the url
 * parameter is <code>null</code>, empty or URL is malformed, nothing is
 * done//  w  w  w . j a va2 s  . c o m
 *
 * @param url
 *            String, may be null or empty
 * @param baseUrl
 *            base for <code>url</code> to add information, which might be
 *            missing in <code>url</code>
 * @return boolean condition returned by the add() method of the underlying
 *         collection
 */
public boolean addURL(String url, URL baseUrl) {
    if (url == null || url.length() == 0) {
        return false;
    }
    //url.replace('+',' ');
    url = StringEscapeUtils.unescapeXml(url);
    boolean b = false;
    try {
        b = this.add(ConversionUtils.makeRelativeURL(baseUrl, url));
    } catch (MalformedURLException mfue) {
        // No WARN message to avoid performance impact
        if (log.isDebugEnabled()) {
            log.debug("Error occured building relative url for:" + url + ", message:" + mfue.getMessage());
        }
        // No point in adding the URL as String as it will result in null 
        // returned during iteration, see URLString
        // See https://bz.apache.org/bugzilla/show_bug.cgi?id=55092
        return false;
    }
    return b;
}

From source file:org.apache.marmotta.ldpath.model.functions.xml.XmlTextFunction.java

@Override
protected String doFilter(String in) {
    return StringEscapeUtils.unescapeXml(RemoveXmlTagsFunction.XML_TAG.matcher(in).replaceAll(""));
}

From source file:org.apache.marmotta.ldpath.model.functions.xml.XmlUnescapeFunction.java

@Override
protected String doFilter(String in) {
    return StringEscapeUtils.unescapeXml(in);
}

From source file:org.cerberus.service.soap.impl.SoapService.java

@Override
public SOAPMessage createSoapRequest(String envelope, String method)
        throws SOAPException, IOException, SAXException, ParserConfigurationException {
    String unescapedEnvelope = StringEscapeUtils.unescapeXml(envelope);
    boolean is12SoapVersion = SOAP_1_2_NAMESPACE_PATTERN.matcher(unescapedEnvelope).matches();

    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("SOAPAction", "\"" + method + "\"");
    headers.addHeader("Content-Type",
            is12SoapVersion ? SOAPConstants.SOAP_1_2_CONTENT_TYPE : SOAPConstants.SOAP_1_1_CONTENT_TYPE);

    InputStream input = new ByteArrayInputStream(unescapedEnvelope.getBytes("UTF-8"));
    MessageFactory messageFactory = MessageFactory
            .newInstance(is12SoapVersion ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL);
    return messageFactory.createMessage(headers, input);
}

From source file:org.cerberus.servlet.crud.testdata.ReadTestDataLib.java

/**
 * Auxiliary method that converts a test data library object to a JSON
 * object./*w ww  . jav a 2 s.c o  m*/
 *
 * @param testDataLib test data library
 * @param unescapeXML indicates whether the XML retrieved in the Envelope
 * should be un-escaped or not.
 * @return JSON object
 * @throws JSONException
 */
private JSONObject convertTestDataLibToJSONObject(TestDataLib testDataLib, boolean unescapeContent)
        throws JSONException {

    if (unescapeContent) {
        //general            
        testDataLib.setDescription(StringEscapeUtils.unescapeHtml4(testDataLib.getDescription()));

        //SQL
        testDataLib.setScript(StringEscapeUtils.unescapeHtml4(testDataLib.getScript()));

        //SOAP
        testDataLib.setServicePath(StringEscapeUtils.unescapeHtml4(testDataLib.getServicePath()));
        testDataLib.setMethod(StringEscapeUtils.unescapeHtml4(testDataLib.getMethod()));
        testDataLib.setEnvelope(StringEscapeUtils.unescapeXml(testDataLib.getEnvelope()));

        //CSV
        testDataLib.setCsvUrl(StringEscapeUtils.unescapeHtml4(testDataLib.getCsvUrl()));
        testDataLib.setSeparator(StringEscapeUtils.unescapeHtml4(testDataLib.getSeparator()));
    }

    Gson gson = new Gson();
    JSONObject result = new JSONObject(gson.toJson(testDataLib));
    return result;
}

From source file:org.codice.ddf.spatial.ogc.wfs.transformer.handlebars.HandlebarsWfsFeatureTransformer.java

private Serializable getValueForAttributeFormat(AttributeType.AttributeFormat attributeFormat,
        final String value) {

    Serializable serializable = null;
    switch (attributeFormat) {
    case BOOLEAN:
        serializable = Boolean.valueOf(value);
        break;/*  w ww .  j a v a2 s  .  co m*/
    case DOUBLE:
        serializable = Double.valueOf(value);
        break;
    case FLOAT:
        serializable = Float.valueOf(value);
        break;
    case INTEGER:
        serializable = Integer.valueOf(value);
        break;
    case LONG:
        serializable = Long.valueOf(value);
        break;
    case SHORT:
        serializable = Short.valueOf(value);
        break;
    case XML:
    case STRING:
        serializable = value;
        break;
    case GEOMETRY:
        LOGGER.trace("Unescape the geometry: {}", value);
        String newValue = StringEscapeUtils.unescapeXml(value);
        LOGGER.debug("Geometry value after it has been xml unescaped: {}", newValue);
        String wkt = getWktFromGeometry(newValue);
        LOGGER.debug("String wkt value: {}", wkt);
        serializable = wkt;
        break;
    case BINARY:
        serializable = value.getBytes(StandardCharsets.UTF_8);
        break;
    case DATE:
        try {
            serializable = DatatypeConverter.parseDate(value).getTime();
        } catch (IllegalArgumentException e) {
            LOGGER.debug("Error converting value to a date. value: '{}'", value, e);
        }
        break;
    default:
        break;
    }
    return serializable;
}