Example usage for org.json.simple JSONObject escape

List of usage examples for org.json.simple JSONObject escape

Introduction

In this page you can find the example usage for org.json.simple JSONObject escape.

Prototype

public static String escape(String s) 

Source Link

Usage

From source file:org.alfresco.repo.jscript.app.JSONConversionComponent.java

/**
 * Handles the work of converting values to JSON.
 * //from  w  w w . j av a2s.  com
 * @param nodeRef NodeRef
 * @param propertyName QName
 * @param key String
 * @param value Serializable
 * @return the JSON value
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object propertyToJSON(final NodeRef nodeRef, final QName propertyName, final String key,
        final Serializable value) {
    if (value != null) {
        // Has a decorator has been registered for this property?
        if (propertyDecorators.containsKey(propertyName)) {
            JSONAware jsonAware = propertyDecorators.get(propertyName).decorate(propertyName, nodeRef, value);
            if (jsonAware != null) {
                return jsonAware;
            }
        } else {
            // Built-in data type processing
            if (value instanceof Date) {
                JSONObject dateObj = new JSONObject();
                dateObj.put("value", JSONObject.escape(value.toString()));
                dateObj.put("iso8601", JSONObject.escape(ISO8601DateFormat.format((Date) value)));
                return dateObj;
            } else if (value instanceof List) {
                // Convert the List to a JSON list by recursively calling propertyToJSON
                List<Object> jsonList = new ArrayList<Object>(((List<Serializable>) value).size());
                for (Serializable listItem : (List<Serializable>) value) {
                    jsonList.add(propertyToJSON(nodeRef, propertyName, key, listItem));
                }
                return jsonList;
            } else if (value instanceof Double) {
                return (Double.isInfinite((Double) value) || Double.isNaN((Double) value) ? null
                        : value.toString());
            } else if (value instanceof Float) {
                return (Float.isInfinite((Float) value) || Float.isNaN((Float) value) ? null
                        : value.toString());
            } else {
                return value.toString();
            }
        }
    }
    return null;
}

From source file:org.arkanos.aos.api.data.Work.java

@Override
public String toString() {
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(1);//  w w w .  jav  a 2  s  .c o m
    df.setGroupingUsed(false);
    SimpleDateFormat sdf = new SimpleDateFormat(Work.DATEFORMAT);
    String result = "{\"";
    try {
        result += "id\":\"" + this.task_id + "_" + sdf.parse(this.start).getTime() + "\",\"";
        result += Work.FIELD_TASK_ID + "\":" + this.task_id + ",\"";
        result += Work.FIELD_START + "\":\"" + this.start.substring(0, this.start.indexOf(".")) + "\",\"";
        result += Work.FIELD_COMMENT + "\":\"" + JSONObject.escape(this.comment) + "\",\"";
        result += Work.FIELD_RESULT + "\":" + this.result + ",\"";
        result += Work.FIELD_TIME_SPENT + "\":" + df.format(this.time_spent / 60.0f) + ",\"";
        result += Work.EXTRA_TASK_NAME + "\":\"" + this.task_name + "\",\"";
        result += Work.EXTRA_GOAL_TITLE + "\":\"" + this.goal_title + "\"}";
    } catch (ParseException e) {
        Log.error("Work", "Problems while parsing Work to a JSON.");
        e.printStackTrace();
        return "{\"error\":\"parsing\"}";
    }
    return result;
}

From source file:org.opensolaris.opengrok.web.JSONSearchServlet.java

@SuppressWarnings({ "unchecked", "deprecation" })
@Override/*ww w  .  j a v a 2s. c o  m*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    JSONObject result = new JSONObject();
    SearchEngine engine = new SearchEngine();

    boolean valid = false;

    String freetext = req.getParameter(PARAM_FREETEXT);
    String def = req.getParameter(PARAM_DEF);
    String symbol = req.getParameter(PARAM_SYMBOL);
    String path = req.getParameter(PARAM_PATH);
    String hist = req.getParameter(PARAM_HIST);

    if (freetext != null) {
        freetext = URLDecoder.decode(freetext);
        engine.setFreetext(freetext);
        valid = true;
        result.put(PARAM_FREETEXT, freetext);
    }

    if (def != null) {
        def = URLDecoder.decode(def);
        engine.setDefinition(def);
        valid = true;
        result.put(PARAM_DEF, def);
    }

    if (symbol != null) {
        symbol = URLDecoder.decode(symbol);
        engine.setSymbol(symbol);
        valid = true;
        result.put(PARAM_SYMBOL, symbol);
    }

    if (path != null) {
        path = URLDecoder.decode(path);
        engine.setFile(path);
        valid = true;
        result.put(PARAM_PATH, path);
    }

    if (hist != null) {
        hist = URLDecoder.decode(hist);
        engine.setHistory(hist);
        valid = true;
        result.put(PARAM_HIST, hist);
    }

    if (valid) {
        long start = System.currentTimeMillis();

        int numResults = engine.search();
        int maxResults = MAX_RESULTS;
        String maxResultsParam = req.getParameter(PARAM_MAXRESULTS);
        if (maxResultsParam != null) {
            try {
                maxResults = Integer.parseInt(maxResultsParam);
                result.put(PARAM_MAXRESULTS, maxResults);
            } catch (NumberFormatException ex) {
            }
        }
        List<Hit> results = new ArrayList<>(maxResults);
        engine.results(0, numResults > maxResults ? maxResults : numResults, results);
        JSONArray resultsArray = new JSONArray();
        for (Hit hit : results) {
            JSONObject hitJson = new JSONObject();
            hitJson.put(ATTRIBUTE_DIRECTORY, JSONObject.escape(hit.getDirectory()));
            hitJson.put(ATTRIBUTE_FILENAME, JSONObject.escape(hit.getFilename()));
            hitJson.put(ATTRIBUTE_LINENO, hit.getLineno());
            hitJson.put(ATTRIBUTE_LINE, conv.encode(hit.getLine()));
            hitJson.put(ATTRIBUTE_PATH, hit.getPath());
            resultsArray.add(hitJson);
        }

        long duration = System.currentTimeMillis() - start;

        result.put(ATTRIBUTE_DURATION, duration);
        result.put(ATTRIBUTE_RESULT_COUNT, results.size());

        result.put(ATTRIBUTE_RESULTS, resultsArray);
    }
    resp.getWriter().write(result.toString());
}

From source file:org.pr.nb.plugins.mongodb.data.MongoDBInstance.java

@Override
public String toJSONString() {
    StringBuilder builder = new StringBuilder("{");
    if (isNotEmpty(hostName)) {
        builder.append(addIndentation(4)).append(JSONObject.escape(FIELD_HOSTNAME)).append(":")
                .append(JSONObject.escape(hostName));
    }/* w  w w  . j a v a  2 s  .c om*/
    if (null != portNumber) {
        builder.append(addIndentation(4)).append(JSONObject.escape(FIELD_PORT)).append(":").append(portNumber);
    }
    if (isNotEmpty(userName)) {
        builder.append(addIndentation(4)).append(JSONObject.escape(FIELD_USERNAME)).append(":")
                .append(JSONObject.escape(userName));
    }
    if (isNotEmpty(displayName)) {
        builder.append(addIndentation(4)).append(JSONObject.escape(FIELD_DISPLAY_NAME)).append(":")
                .append(JSONObject.escape(displayName));
    }

    builder.append("}");
    return builder.toString();
}

From source file:org.zaizi.alfresco.redlink.service.redlink.RedLinkEnhancerServiceImpl.java

/**
 * Enhance a nodeRef with Entity Annotations as categories
 * //from   w w  w  . ja v  a2  s  . com
 * @param nodeRef
 * @throws ContentIOException
 * @throws IOException
 */
private void enhanceAnnotations(final NodeRef nodeRef, Enhancements enhancements)
        throws ContentIOException, IOException, InterruptedException {
    List<EntityAnnotation> entityAnnotations = new ArrayList<EntityAnnotation>(
            enhancements.getEntityAnnotationsByConfidenceValue(confidenceThreshold));

    if (logger.isDebugEnabled()) {
        logger.debug("Found " + entityAnnotations.size() + " entity annotations for nodeRef: " + nodeRef
                + " with a conficende over: " + confidenceThreshold);
    }
    final Set<NodeRef> cats = new LinkedHashSet<NodeRef>();

    for (EntityAnnotation entity : entityAnnotations) {
        // sanitize entity label for category name compatibility
        final String entityLabel = sanitize(entity.getEntityLabel());

        Set<String> entityTypes = (Set<String>) entity.getEntityTypes();
        final String type = entityTypeExtractor.getType(entityTypes);
        final NodeRef cat;
        if (type != null) {
            cat = transactionService.getRetryingTransactionHelper()
                    .doInTransaction(new RetryingTransactionCallback<NodeRef>() {
                        @Override
                        public NodeRef execute() throws Throwable {
                            return AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>() {
                                @Override
                                public NodeRef doWork() {
                                    final NodeRef cat = getCategory(type, entityLabel);
                                    return cat;
                                }
                            });
                        }
                    }, false, true);

            if (nodeService.exists(cat)) {
                cats.add(cat);

                final Map<QName, Serializable> props = nodeService.getProperties(cat);

                String comment = entity.getEntityReference().getValue(RDFS.COMMENT.toString(), DEFAULT_LANG);

                String abstractString = StringUtils.EMPTY;
                if (comment != null && !comment.isEmpty()) {
                    abstractString = JSONObject.escape(comment);
                }

                String thumbnail = StringUtils.EMPTY;

                thumbnail = entity.getEntityReference().getFirstPropertyValue(DEPICTION);

                props.put(SensefyModel.PROP_URI, entity.getEntityReference().getUri());
                props.put(SensefyModel.PROP_LABEL, entity.getEntityLabel());
                props.put(SensefyModel.PROP_ABSTRACT, abstractString);
                props.put(SensefyModel.PROP_THUMBNAIL, thumbnail);
                props.put(SensefyModel.PROP_TYPES, (Serializable) entityTypes);

                // Update category properties using system user and retrying if concurrent errors
                transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<Void>() {
                            @Override
                            public Void execute() throws Throwable {
                                AuthenticationUtil.runAsSystem(new RunAsWork<Void>() {
                                    @Override
                                    public Void doWork() {
                                        if (nodeService.exists(cat)) {
                                            nodeService.setProperties(cat, props);
                                        }
                                        return null;
                                    }
                                });
                                return null;
                            }
                        }, false, true);
            }
        }
    }

    if (cats != null && !cats.isEmpty()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Setting " + cats.size() + " categories to node: " + nodeRef);
        }

        behaviourFilter.disableBehaviour(nodeRef);
        nodeService.setProperty(nodeRef, ContentModel.PROP_CATEGORIES, (Serializable) cats);
        behaviourFilter.enableBehaviour(nodeRef);
    }
}

From source file:pt.ist.fenixedu.teacher.ui.struts.action.gep.a3es.A3ESDegreeProcess.java

private String getTeachersAndTeachingHours(CurricularCourse course, boolean responsibleTeacher) {
    Map<Teacher, Double> responsiblesMap = new HashMap<Teacher, Double>();
    List<ExecutionSemester> executionSemesters = getSelectedExecutionSemesters();
    for (final ExecutionCourse executionCourse : course.getAssociatedExecutionCoursesSet()) {
        if (executionSemesters.contains(executionCourse.getExecutionPeriod())) {
            for (Professorship professorhip : executionCourse.getProfessorshipsSet()) {
                if (professorhip.isResponsibleFor() == responsibleTeacher
                        && PersonProfessionalData.isTeacherActiveOrHasAuthorizationForSemester(
                                professorhip.getPerson().getTeacher(), executionCourse.getExecutionPeriod())) {
                    Double hours = responsiblesMap.get(professorhip.getTeacher());
                    if (hours == null) {
                        hours = 0.0;//from  ww w  . j a v a2s  .  co m
                    }
                    hours = hours + getHours(professorhip);
                    responsiblesMap.put(professorhip.getTeacher(), hours);
                }
            }
        }
    }
    int counter = 1000;
    List<String> responsibles = new ArrayList<String>();
    for (Teacher teacher : responsiblesMap.keySet()) {
        String responsible = (responsibleTeacher ? teacher.getPerson().getFirstAndLastName()
                : teacher.getPerson().getName()) + " (" + responsiblesMap.get(teacher) + ")";
        counter -= JSONObject.escape(responsible + ", ").getBytes().length;
        responsibles.add(responsible);
    }

    if (!responsibleTeacher && course.isDissertation()) {
        Set<Teacher> teachers = new HashSet<Teacher>();
        for (ExecutionCourse executionCourse : course.getAssociatedExecutionCoursesSet()) {
            if (executionCourse.getExecutionPeriod().getExecutionYear()
                    .equals(executionSemester.getExecutionYear().getPreviousExecutionYear())) {
                for (Attends attends : executionCourse.getAttendsSet()) {
                    if (attends.getEnrolment() != null && attends.getEnrolment().getThesis() != null) {
                        for (ThesisEvaluationParticipant thesisEvaluationParticipant : attends.getEnrolment()
                                .getThesis().getOrientation()) {
                            if (thesisEvaluationParticipant.getPerson().getTeacher() != null
                                    && PersonProfessionalData.isTeacherActiveOrHasAuthorizationForSemester(
                                            thesisEvaluationParticipant.getPerson().getTeacher(),
                                            executionCourse.getExecutionPeriod())) {
                                teachers.add(thesisEvaluationParticipant.getPerson().getTeacher());
                            }
                        }
                    }
                }
            }
        }
        for (Teacher teacher : teachers) {
            String responsible = (responsibleTeacher ? teacher.getPerson().getFirstAndLastName()
                    : teacher.getPerson().getName()) + " (0.0)";
            if (counter - JSONObject.escape(responsible).getBytes().length < 0) {
                break;
            }
            if (!responsiblesMap.containsKey(teacher)) {
                counter -= JSONObject.escape(responsible + ", ").getBytes().length;
                responsibles.add(responsible);
            }
        }
    }

    return StringUtils.join(responsibles, ", ");
}