Search in sources :

Example 1 with StringUtils.replace

use of org.apache.commons.lang3.StringUtils.replace in project Gargoyle by callakrsos.

the class MysqlPane method menuExportInsertScriptOnAction.

@Override
public void menuExportInsertScriptOnAction(ActionEvent e) {
    Optional<Pair<String, String[]>> showTableInputDialog = showTableInputDialog(f -> f.getName());
    // DialogUtil.showInputDialog("table Name", "테이블명을 입력하세요.");
    if (showTableInputDialog == null)
        return;
    showTableInputDialog.ifPresent(op -> {
        if (op == null || op.getValue() == null)
            return;
        String schemaName = op.getValue()[0];
        String _tableName = op.getValue()[1];
        String tableName = "";
        if (ValueUtil.isNotEmpty(schemaName)) {
            tableName = String.format("`%s`.%s", schemaName, _tableName);
        }
        ObservableList<Map<String, Object>> items = getTbResult().getItems();
        Map<String, Object> map = items.get(0);
        final Set<String> keySet = map.keySet();
        StringBuilder clip = new StringBuilder();
        String insertPreffix = "insert into " + tableName;
        String collect = keySet.stream().collect(Collectors.joining(",", "(", ")"));
        String insertMiddle = " values ";
        List<String> valueList = items.stream().map(v -> {
            return ValueUtil.toJSONObject(v);
        }).map(v -> {
            Iterator<String> iterator = keySet.iterator();
            List<Object> values = new ArrayList<>();
            while (iterator.hasNext()) {
                String columnName = iterator.next();
                Object value = v.get(columnName);
                values.add(value);
            }
            return values;
        }).map(list -> {
            return list.stream().map(str -> {
                if (str == null)
                    return null;
                else {
                    String convert = str.toString();
                    convert = convert.substring(1, convert.length() - 1);
                    if (convert.indexOf("'") >= 0) {
                        try {
                            convert = StringUtils.replace(convert, "'", "''");
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                    return "'".concat(convert).concat("'");
                }
            }).collect(Collectors.joining(",", "(", ")"));
        }).map(str -> {
            return new StringBuilder().append(insertPreffix).append(collect).append(insertMiddle).append(str).append(";\n").toString();
        }).collect(Collectors.toList());
        valueList.forEach(str -> {
            clip.append(str);
        });
        SimpleTextView parent = new SimpleTextView(clip.toString());
        parent.setWrapText(false);
        FxUtil.createStageAndShow(String.format("[InsertScript] Table : %s", tableName), parent, stage -> {
        });
    });
}
Also used : Connection(java.sql.Connection) TreeItem(javafx.scene.control.TreeItem) DialogUtil(com.kyj.fx.voeditor.visual.util.DialogUtil) Supplier(java.util.function.Supplier) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) TableItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.TableItemTree) Map(java.util.Map) MySQLDatabaseItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.mysql.MySQLDatabaseItemTree) Pair(javafx.util.Pair) Iterator(java.util.Iterator) DatabaseTreeNode(com.kyj.fx.voeditor.visual.component.sql.dbtree.DatabaseTreeNode) Set(java.util.Set) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) SimpleTextView(com.kyj.fx.voeditor.visual.component.text.SimpleTextView) ConfigResourceLoader(com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader) Collectors(java.util.stream.Collectors) FxUtil(com.kyj.fx.voeditor.visual.util.FxUtil) List(java.util.List) ResourceLoader(com.kyj.fx.voeditor.visual.momory.ResourceLoader) ActionEvent(javafx.event.ActionEvent) Stage(javafx.stage.Stage) DatabaseItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.DatabaseItemTree) Optional(java.util.Optional) ObservableList(javafx.collections.ObservableList) Iterator(java.util.Iterator) SimpleTextView(com.kyj.fx.voeditor.visual.component.text.SimpleTextView) ArrayList(java.util.ArrayList) List(java.util.List) ObservableList(javafx.collections.ObservableList) Map(java.util.Map) Pair(javafx.util.Pair)

Example 2 with StringUtils.replace

use of org.apache.commons.lang3.StringUtils.replace in project eol-globi-data by jhpoelen.

the class StudyImporterForHurlbert method importInteraction.

protected void importInteraction(Set<String> regions, Set<String> locales, Set<String> habitats, Record record, Study study, String preyTaxonName, String predatorName) throws StudyImporterException {
    try {
        Taxon predatorTaxon = new TaxonImpl(predatorName);
        Specimen predatorSpecimen = nodeFactory.createSpecimen(study, predatorTaxon);
        setBasisOfRecordAsLiterature(predatorSpecimen);
        Taxon preyTaxon = new TaxonImpl(preyTaxonName);
        String preyNameId = StringUtils.trim(columnValueOrNull(record, "Prey_Name_ITIS_ID"));
        if (NumberUtils.isDigits(preyNameId)) {
            preyTaxon.setExternalId(TaxonomyProvider.ITIS.getIdPrefix() + preyNameId);
        }
        Specimen preySpecimen = nodeFactory.createSpecimen(study, preyTaxon);
        setBasisOfRecordAsLiterature(preySpecimen);
        String preyStage = StringUtils.trim(columnValueOrNull(record, "Prey_Stage"));
        if (StringUtils.isNotBlank(preyStage)) {
            Term lifeStage = nodeFactory.getOrCreateLifeStage("HULBERT:" + StringUtils.replace(preyStage, " ", "_"), preyStage);
            preySpecimen.setLifeStage(lifeStage);
        }
        String preyPart = StringUtils.trim(columnValueOrNull(record, "Prey_Part"));
        if (StringUtils.isNotBlank(preyPart)) {
            Term term = nodeFactory.getOrCreateBodyPart("HULBERT:" + StringUtils.replace(preyPart, " ", "_"), preyPart);
            preySpecimen.setBodyPart(term);
        }
        Date date = addCollectionDate(record, study);
        nodeFactory.setUnixEpochProperty(predatorSpecimen, date);
        nodeFactory.setUnixEpochProperty(preySpecimen, date);
        LocationImpl location = new LocationImpl(null, null, null, null);
        String longitude = columnValueOrNull(record, "Longitude_dd");
        String latitude = columnValueOrNull(record, "Latitude_dd");
        if (NumberUtils.isNumber(latitude) && NumberUtils.isNumber(longitude)) {
            try {
                LatLng latLng = LocationUtil.parseLatLng(latitude, longitude);
                String altitude = columnValueOrNull(record, "Altitude_mean_m");
                Double altitudeD = NumberUtils.isNumber(altitude) ? Double.parseDouble(altitude) : null;
                location = new LocationImpl(latLng.getLat(), latLng.getLng(), altitudeD, null);
            } catch (InvalidLocationException e) {
                getLogger().warn(study, "found invalid (lat,lng) pair: (" + latitude + "," + longitude + ")");
            }
        }
        String locationRegion = columnValueOrNull(record, "Location_Region");
        String locationSpecific = columnValueOrNull(record, "Location_Specific");
        location.setLocality(StringUtils.join(Arrays.asList(locationRegion, locationSpecific), ":"));
        Location locationNode = nodeFactory.getOrCreateLocation(location);
        String habitat_type = columnValueOrNull(record, "Habitat_type");
        List<Term> habitatList = Arrays.stream(StringUtils.split(StringUtils.defaultIfBlank(habitat_type, ""), ";")).map(StringUtils::trim).map(habitat -> new TermImpl(idForHabitat(habitat), habitat)).collect(Collectors.toList());
        nodeFactory.addEnvironmentToLocation(locationNode, habitatList);
        preySpecimen.caughtIn(locationNode);
        predatorSpecimen.caughtIn(locationNode);
        predatorSpecimen.ate(preySpecimen);
    } catch (NodeFactoryException e) {
        throw new StudyImporterException("failed to create interaction between [" + predatorName + "] and [" + preyTaxonName + "]", e);
    }
}
Also used : TsvParser(com.univocity.parsers.tsv.TsvParser) DateUtil(org.eol.globi.util.DateUtil) StringUtils(org.apache.commons.lang.StringUtils) CitationUtil(org.globalbioticinteractions.dataset.CitationUtil) Arrays(java.util.Arrays) Record(com.univocity.parsers.common.record.Record) Term(org.eol.globi.domain.Term) Specimen(org.eol.globi.domain.Specimen) Location(org.eol.globi.domain.Location) Date(java.util.Date) TermImpl(org.eol.globi.domain.TermImpl) LocationImpl(org.eol.globi.domain.LocationImpl) HashMap(java.util.HashMap) StudyImpl(org.eol.globi.domain.StudyImpl) HashSet(java.util.HashSet) TaxonImpl(org.eol.globi.domain.TaxonImpl) Map(java.util.Map) LatLng(org.eol.globi.geo.LatLng) TaxonomyProvider(org.eol.globi.domain.TaxonomyProvider) Taxon(org.eol.globi.domain.Taxon) InvalidLocationException(org.eol.globi.util.InvalidLocationException) DateTime(org.joda.time.DateTime) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) TsvParserSettings(com.univocity.parsers.tsv.TsvParserSettings) List(java.util.List) NumberUtils(org.apache.commons.lang3.math.NumberUtils) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Study(org.eol.globi.domain.Study) StringEscapeUtils(org.apache.commons.lang.StringEscapeUtils) ArrayUtils(org.apache.commons.lang.ArrayUtils) InputStream(java.io.InputStream) InvalidLocationException(org.eol.globi.util.InvalidLocationException) Taxon(org.eol.globi.domain.Taxon) TaxonImpl(org.eol.globi.domain.TaxonImpl) Term(org.eol.globi.domain.Term) Date(java.util.Date) TermImpl(org.eol.globi.domain.TermImpl) Specimen(org.eol.globi.domain.Specimen) StringUtils(org.apache.commons.lang.StringUtils) LocationImpl(org.eol.globi.domain.LocationImpl) LatLng(org.eol.globi.geo.LatLng) Location(org.eol.globi.domain.Location)

Example 3 with StringUtils.replace

use of org.apache.commons.lang3.StringUtils.replace in project symja_android_library by axkr.

the class Pods method createResult.

public static ObjectNode createResult(String inputStr, int formats, boolean strictSymja) {
    ObjectNode messageJSON = JSON_OBJECT_MAPPER.createObjectNode();
    ObjectNode queryresult = JSON_OBJECT_MAPPER.createObjectNode();
    messageJSON.putPOJO("queryresult", queryresult);
    queryresult.put("success", "false");
    queryresult.put("error", "false");
    queryresult.put("numpods", 0);
    queryresult.put("version", "0.1");
    boolean error = false;
    int numpods = 0;
    IExpr inExpr = S.Null;
    IExpr outExpr = S.Null;
    EvalEngine engine = EvalEngine.get();
    ArrayNode podsArray = JSON_OBJECT_MAPPER.createArrayNode();
    if (strictSymja) {
        engine.setPackageMode(false);
        final ExprParser parser = new ExprParser(engine, true);
        try {
            inExpr = parser.parse(inputStr);
            if (inExpr.isPresent()) {
                long numberOfLeaves = inExpr.leafCount();
                if (numberOfLeaves < Config.MAX_INPUT_LEAVES) {
                    outExpr = inExpr;
                    final StringWriter errorWriter = new StringWriter();
                    WriterOutputStream werrors = new WriterOutputStream(errorWriter);
                    PrintStream errors = new PrintStream(werrors);
                    IExpr firstEval = F.NIL;
                    try (ThreadLocalNotifierClosable c = setLogEventNotifier(errors)) {
                        engine.setErrorPrintStream(errors);
                        firstEval = engine.evaluateNIL(inExpr);
                    } finally {
                        engine.setErrorPrintStream(null);
                    }
                    addSymjaPod(podsArray, inExpr, inExpr, "Input", "Identity", formats, engine);
                    numpods++;
                    String errorString = "";
                    if (firstEval.isPresent()) {
                        outExpr = firstEval;
                    } else {
                        errorString = errorWriter.toString().trim();
                    }
                    outExpr = engine.evaluate(inExpr);
                    if (outExpr instanceof GraphExpr) {
                        String javaScriptStr = GraphFunctions.graphToJSForm((GraphExpr) outExpr);
                        if (javaScriptStr != null) {
                            String html = VISJS_IFRAME;
                            html = StringUtils.replace(html, "`1`", javaScriptStr);
                            html = // 
                            StringUtils.replace(// 
                            html, // 
                            "`2`", // 
                            "  var options = { };\n");
                            // html = StringEscapeUtils.escapeHtml4(html);
                            int form = internFormat(SYMJA, "visjs");
                            addPod(podsArray, inExpr, outExpr, html, "Graph data", "Graph", form, engine);
                            numpods++;
                        } else {
                            addSymjaPod(podsArray, inExpr, outExpr, errorString, "Evaluated result", "Expression", formats, engine, true);
                            numpods++;
                        }
                    } else {
                        addSymjaPod(podsArray, inExpr, outExpr, errorString, "Evaluated result", "Expression", formats, engine, true);
                        numpods++;
                    }
                    resultStatistics(queryresult, error, numpods, podsArray);
                    return messageJSON;
                }
            }
        } catch (SyntaxError serr) {
            // this includes syntax errors
            LOGGER.debug("Pods.createResult() failed", serr);
            return errorJSON("0", serr.getMessage());
        }
        queryresult.put("error", error ? "true" : "false");
        return messageJSON;
    }
    inExpr = parseInput(inputStr, engine);
    if (inExpr.isPresent()) {
        long numberOfLeaves = inExpr.leafCount();
        if (numberOfLeaves < Config.MAX_INPUT_LEAVES) {
            outExpr = inExpr;
            final StringWriter errorWriter = new StringWriter();
            WriterOutputStream werrors = new WriterOutputStream(errorWriter);
            PrintStream errors = new PrintStream(werrors);
            IExpr firstEval = F.NIL;
            try (ThreadLocalNotifierClosable c = setLogEventNotifier(errors)) {
                engine.setErrorPrintStream(errors);
                firstEval = engine.evaluateNIL(inExpr);
            } finally {
                engine.setErrorPrintStream(null);
            }
            addSymjaPod(podsArray, inExpr, inExpr, "Input", "Identity", formats, engine);
            numpods++;
            String errorString = "";
            if (firstEval.isPresent()) {
                outExpr = firstEval;
            } else {
                errorString = errorWriter.toString().trim();
            }
            IExpr podOut = outExpr;
            IExpr numExpr = F.NIL;
            IExpr evaledNumExpr = F.NIL;
            if (outExpr.isNumericFunction(true)) {
                numExpr = inExpr.isAST(S.N) ? inExpr : F.N(inExpr);
                evaledNumExpr = engine.evaluate(F.N(outExpr));
            }
            if (outExpr.isNumber() || outExpr.isQuantity()) {
                if (outExpr.isInteger()) {
                    numpods += integerPods(podsArray, inExpr, (IInteger) outExpr, formats, engine);
                    resultStatistics(queryresult, error, numpods, podsArray);
                    return messageJSON;
                } else {
                    podOut = outExpr;
                    if (outExpr.isRational()) {
                        addSymjaPod(podsArray, inExpr, podOut, "Exact result", "Rational", formats, engine);
                        numpods++;
                    }
                    if (// 
                    numExpr.isPresent() && (evaledNumExpr.isInexactNumber() || evaledNumExpr.isQuantity())) {
                        addSymjaPod(podsArray, numExpr, evaledNumExpr, "Decimal form", "Numeric", formats, engine);
                        numpods++;
                        if (!outExpr.isRational()) {
                            if (evaledNumExpr.isInexactNumber()) {
                                inExpr = F.Rationalize(evaledNumExpr);
                                podOut = engine.evaluate(inExpr);
                                addSymjaPod(podsArray, inExpr, podOut, "Rational form", "Numeric", formats, engine);
                                numpods++;
                            }
                        }
                    }
                    if (outExpr.isFraction()) {
                        IFraction frac = (IFraction) outExpr;
                        if (!frac.integerPart().equals(F.C0)) {
                            inExpr = F.List(F.IntegerPart(outExpr), F.FractionalPart(outExpr));
                            podOut = engine.evaluate(inExpr);
                            String plaintext = podOut.first().toString() + " " + podOut.second().toString();
                            addSymjaPod(podsArray, inExpr, podOut, plaintext, "Mixed fraction", "Rational", formats, engine);
                            numpods++;
                            inExpr = F.ContinuedFraction(outExpr);
                            podOut = engine.evaluate(inExpr);
                            StringBuilder plainBuf = new StringBuilder();
                            if (podOut.isNonEmptyList()) {
                                IAST list = (IAST) podOut;
                                plainBuf.append('[');
                                plainBuf.append(list.arg1().toString());
                                plainBuf.append(';');
                                for (int i = 2; i < list.size(); i++) {
                                    plainBuf.append(' ');
                                    plainBuf.append(list.get(i).toString());
                                    if (i < list.size() - 1) {
                                        plainBuf.append(',');
                                    }
                                }
                                plainBuf.append(']');
                            }
                            addSymjaPod(podsArray, inExpr, podOut, plainBuf.toString(), "Continued fraction", "ContinuedFraction", formats, engine);
                            numpods++;
                        }
                    }
                    resultStatistics(queryresult, error, numpods, podsArray);
                    return messageJSON;
                }
            } else {
                if (outExpr.isAST(S.Plot, 2) && outExpr.first().isList()) {
                    outExpr = outExpr.first();
                }
                if (outExpr.isList()) {
                    IAST list = (IAST) outExpr;
                    ListPod listPod = new ListPod(list);
                    numpods += listPod.addJSON(podsArray, formats, engine);
                }
                if (// 
                numExpr.isPresent() && (evaledNumExpr.isInexactNumber() || evaledNumExpr.isQuantity())) {
                    addSymjaPod(podsArray, numExpr, evaledNumExpr, "Decimal form", "Numeric", formats, engine);
                    numpods++;
                }
                if (outExpr.isSymbol() || outExpr.isString()) {
                    String inputWord = outExpr.toString();
                    StringBuilder buf = new StringBuilder();
                    // }
                    if (outExpr.isSymbol() && Documentation.getMarkdown(buf, inputWord)) {
                        numpods += DocumentationPod.addDocumentationPod(new DocumentationPod((ISymbol) outExpr), podsArray, buf, formats);
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else {
                        if (outExpr.isString()) {
                            int mimeTyp = ((IStringX) outExpr).getMimeType();
                            if (mimeTyp == IStringX.APPLICATION_SYMJA || mimeTyp == IStringX.APPLICATION_JAVA || mimeTyp == IStringX.APPLICATION_JAVASCRIPT) {
                                String html = toHighligthedCode(outExpr.toString());
                                addSymjaPod(podsArray, inExpr, F.NIL, html, "Result", "String form", HTML, engine);
                                numpods++;
                                resultStatistics(queryresult, error, numpods, podsArray);
                                return messageJSON;
                            } else if (outExpr.isString()) {
                                podOut = outExpr;
                                addSymjaPod(podsArray, inExpr, podOut, "String form", "String", formats, engine);
                                numpods++;
                            }
                        }
                        ArrayList<IPod> soundsLike = listOfPods(inputWord);
                        if (soundsLike != null) {
                            boolean evaled = false;
                            for (int i = 0; i < soundsLike.size(); i++) {
                                IPod pod = soundsLike.get(i);
                                if (pod.keyWord().equalsIgnoreCase(inputWord)) {
                                    int numberOfEntries = pod.addJSON(podsArray, formats, engine);
                                    if (numberOfEntries > 0) {
                                        numpods += numberOfEntries;
                                        evaled = true;
                                        break;
                                    }
                                }
                            }
                            if (!evaled) {
                                for (int i = 0; i < soundsLike.size(); i++) {
                                    IPod pod = soundsLike.get(i);
                                    int numberOfEntries = pod.addJSON(podsArray, formats, engine);
                                    if (numberOfEntries > 0) {
                                        numpods += numberOfEntries;
                                    }
                                }
                            }
                            resultStatistics(queryresult, error, numpods, podsArray);
                            return messageJSON;
                        }
                    }
                } else {
                    if (inExpr.isAST(S.D, 2, 3)) {
                        if (inExpr.isAST1()) {
                            VariablesSet varSet = new VariablesSet(inExpr.first());
                            IAST variables = varSet.getVarList();
                            IASTAppendable result = ((IAST) inExpr).copyAppendable();
                            result.appendArgs(variables);
                            inExpr = result;
                        }
                        outExpr = engine.evaluate(inExpr);
                        podOut = outExpr;
                        addSymjaPod(podsArray, inExpr, podOut, "Derivative", "Derivative", formats, engine);
                        numpods++;
                        if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                            inExpr = F.TrigToExp(outExpr);
                            podOut = engine.evaluate(inExpr);
                            // if (!S.PossibleZeroQ.ofQ(engine, F.Subtract(podOut, outExpr))) {
                            if (!podOut.equals(outExpr)) {
                                addSymjaPod(// 
                                podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else if (inExpr.isAST(S.Integrate, 2, 3)) {
                        if (inExpr.isAST1()) {
                            VariablesSet varSet = new VariablesSet(inExpr.first());
                            IAST variables = varSet.getVarList();
                            IASTAppendable result = ((IAST) inExpr).copyAppendable();
                            result.appendArgs(variables);
                            inExpr = result;
                        }
                        outExpr = engine.evaluate(inExpr);
                        podOut = outExpr;
                        addSymjaPod(podsArray, inExpr, podOut, "Integration", "Integral", formats, engine);
                        numpods++;
                        if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                            inExpr = F.TrigToExp(outExpr);
                            podOut = engine.evaluate(inExpr);
                            if (!podOut.equals(outExpr)) {
                                addSymjaPod(podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else if (inExpr.isAST(S.Solve, 2, 4)) {
                        if (inExpr.isAST1()) {
                            VariablesSet varSet = new VariablesSet(inExpr.first());
                            IAST variables = varSet.getVarList();
                            IASTAppendable result = ((IAST) inExpr).copyAppendable();
                            result.append(variables);
                            inExpr = result;
                        }
                        outExpr = engine.evaluate(inExpr);
                        podOut = outExpr;
                        addSymjaPod(podsArray, inExpr, podOut, "Solve equation", "Solver", formats, engine);
                        numpods++;
                        if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                            inExpr = F.TrigToExp(outExpr);
                            podOut = engine.evaluate(inExpr);
                            // if (!S.PossibleZeroQ.ofQ(engine, F.Subtract(podOut, outExpr))) {
                            if (!podOut.equals(outExpr)) {
                                addSymjaPod(// 
                                podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else {
                        IExpr expr = inExpr;
                        if (outExpr.isAST(S.JSFormData, 3)) {
                            podOut = outExpr;
                            int form = internFormat(SYMJA, podOut.second().toString());
                            addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(inExpr), "Function", "Plotter", form, engine);
                            numpods++;
                        } else if (outExpr instanceof GraphExpr) {
                            String javaScriptStr = GraphFunctions.graphToJSForm((GraphExpr) outExpr);
                            if (javaScriptStr != null) {
                                String html = VISJS_IFRAME;
                                html = StringUtils.replace(html, "`1`", javaScriptStr);
                                html = // 
                                StringUtils.replace(// 
                                html, // 
                                "`2`", // 
                                "  var options = { };\n");
                                // html = StringEscapeUtils.escapeHtml4(html);
                                int form = internFormat(SYMJA, "visjs");
                                addPod(podsArray, inExpr, podOut, html, "Graph data", "Graph", form, engine);
                                numpods++;
                            }
                        } else {
                            IExpr head = outExpr.head();
                            if (head instanceof IBuiltInSymbol && outExpr.size() > 1) {
                                IEvaluator evaluator = ((IBuiltInSymbol) head).getEvaluator();
                                if (evaluator instanceof IDistribution) {
                                    // if (evaluator instanceof IDiscreteDistribution) {
                                    int snumpods = statisticsPods(podsArray, (IAST) outExpr, podOut, formats, engine);
                                    numpods += snumpods;
                                }
                            }
                            VariablesSet varSet = new VariablesSet(outExpr);
                            IAST variables = varSet.getVarList();
                            if (outExpr.isBooleanFormula()) {
                                numpods += booleanPods(podsArray, outExpr, variables, formats, engine);
                            }
                            if (outExpr.isAST(S.Equal, 3)) {
                                IExpr arg1 = outExpr.first();
                                IExpr arg2 = outExpr.second();
                                if (// 
                                arg1.isNumericFunction(varSet) && arg2.isNumericFunction(varSet)) {
                                    if (variables.argSize() == 1) {
                                        IExpr plot2D = F.Plot(F.List(arg1, arg2), F.List(variables.arg1(), F.num(-20), F.num(20)));
                                        podOut = engine.evaluate(plot2D);
                                        if (podOut.isAST(S.JSFormData, 3)) {
                                            int form = internFormat(SYMJA, podOut.second().toString());
                                            addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(plot2D), "Function", "Plotter", form, engine);
                                            numpods++;
                                        }
                                    }
                                    if (!arg1.isZero() && !arg2.isZero()) {
                                        inExpr = F.Equal(engine.evaluate(F.Subtract(arg1, arg2)), F.C0);
                                        podOut = inExpr;
                                        addSymjaPod(podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                        numpods++;
                                    }
                                    inExpr = F.Solve(F.binaryAST2(S.Equal, arg1, arg2), variables);
                                    podOut = engine.evaluate(inExpr);
                                    addSymjaPod(podsArray, inExpr, podOut, "Solution", "Reduce", formats, engine);
                                    numpods++;
                                }
                                resultStatistics(queryresult, error, numpods, podsArray);
                                return messageJSON;
                            } else {
                                if (!inExpr.equals(outExpr)) {
                                    addSymjaPod(podsArray, inExpr, outExpr, "Result", "Identity", formats, engine);
                                    numpods++;
                                }
                            }
                            boolean isNumericFunction = outExpr.isNumericFunction(varSet);
                            if (isNumericFunction) {
                                if (variables.argSize() == 1) {
                                    IExpr plot2D = F.Plot(outExpr, F.List(variables.arg1(), F.num(-7), F.num(7)));
                                    podOut = engine.evaluate(plot2D);
                                    if (podOut.isAST(S.JSFormData, 3)) {
                                        int form = internFormat(SYMJA, podOut.second().toString());
                                        addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(plot2D), "Function", "Plotter", form, engine);
                                        numpods++;
                                    }
                                } else if (variables.argSize() == 2) {
                                    IExpr plot3D = F.Plot3D(outExpr, F.List(variables.arg1(), F.num(-3.5), F.num(3.5)), F.List(variables.arg2(), F.num(-3.5), F.num(3.5)));
                                    podOut = engine.evaluate(plot3D);
                                    if (podOut.isAST(S.JSFormData, 3)) {
                                        int form = internFormat(SYMJA, podOut.second().toString());
                                        addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(plot3D), "3D plot", "Plot", form, engine);
                                        numpods++;
                                    }
                                }
                            }
                            if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                                inExpr = F.TrigToExp(outExpr);
                                podOut = engine.evaluate(inExpr);
                                // {
                                if (!podOut.equals(outExpr)) {
                                    addSymjaPod(podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                    numpods++;
                                }
                            }
                            if (isNumericFunction && variables.argSize() == 1) {
                                if (outExpr.isPolynomial(variables) && !outExpr.isAtom()) {
                                    inExpr = F.Factor(outExpr);
                                    podOut = engine.evaluate(inExpr);
                                    addSymjaPod(podsArray, inExpr, podOut, "Factor", "Polynomial", formats, engine);
                                    numpods++;
                                    IExpr x = variables.first();
                                    inExpr = F.Minimize(outExpr, x);
                                    podOut = engine.evaluate(inExpr);
                                    if (podOut.isAST(S.List, 3) && podOut.first().isNumber() && podOut.second().isAST(S.List, 2)) {
                                        IExpr rule = podOut.second().first();
                                        if (rule.isRule()) {
                                            StringBuilder buf = new StringBuilder();
                                            buf.append("min{");
                                            buf.append(outExpr.toString());
                                            buf.append("} = ");
                                            buf.append(podOut.first());
                                            buf.append(" at ");
                                            buf.append(rule.first().toString());
                                            buf.append(" = ");
                                            buf.append(rule.second().toString());
                                            addSymjaPod(podsArray, inExpr, podOut, buf.toString(), "GlobalExtrema", "GlobalMinimum", formats, engine);
                                            numpods++;
                                        }
                                    }
                                    inExpr = F.Maximize(outExpr, x);
                                    podOut = engine.evaluate(inExpr);
                                    if (podOut.isAST(S.List, 3) && podOut.first().isNumber() && podOut.second().isAST(S.List, 2)) {
                                        IExpr rule = podOut.second().first();
                                        if (rule.isRule()) {
                                            StringBuilder buf = new StringBuilder();
                                            buf.append("max{");
                                            buf.append(outExpr.toString());
                                            buf.append("} = ");
                                            buf.append(podOut.first());
                                            buf.append(" at ");
                                            buf.append(rule.first().toString());
                                            buf.append(" = ");
                                            buf.append(rule.second().toString());
                                            addSymjaPod(podsArray, inExpr, podOut, buf.toString(), "GlobalExtrema", "GlobalMaximum", formats, engine);
                                            numpods++;
                                        }
                                    }
                                }
                                inExpr = F.D(outExpr, variables.arg1());
                                podOut = engine.evaluate(inExpr);
                                addSymjaPod(podsArray, inExpr, podOut, "Derivative", "Derivative", formats, engine);
                                numpods++;
                                inExpr = F.Integrate(outExpr, variables.arg1());
                                podOut = engine.evaluate(inExpr);
                                addSymjaPod(podsArray, inExpr, podOut, "Indefinite integral", "Integral", formats, engine);
                                numpods++;
                            }
                        }
                        if (numpods == 1) {
                            // only Identity pod was appended
                            if (// 
                            errorString.length() == 0 && !firstEval.isPresent()) {
                                addSymjaPod(podsArray, expr, outExpr, "Evaluated result", "Expression", formats, engine);
                                numpods++;
                            } else {
                                addSymjaPod(podsArray, expr, outExpr, errorString, "Evaluated result", "Expression", formats, engine, true);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    }
                }
            }
            if (numpods > 0) {
                resultStatistics(queryresult, error, numpods, podsArray);
                return messageJSON;
            }
        }
    }
    queryresult.put("error", error ? "true" : "false");
    return messageJSON;
}
Also used : IStringX(org.matheclipse.core.interfaces.IStringX) Level(org.apache.logging.log4j.Level) IInteger(org.matheclipse.core.interfaces.IInteger) StringUtils(org.apache.commons.lang3.StringUtils) ThreadLocalNotifyingAppender(org.matheclipse.logging.ThreadLocalNotifyingAppender) TeXUtilities(org.matheclipse.core.eval.TeXUtilities) IDistribution(org.matheclipse.core.interfaces.IDistribution) Trie(org.matheclipse.parser.trie.Trie) VariablesSet(org.matheclipse.core.convert.VariablesSet) Map(java.util.Map) EvalEngine(org.matheclipse.core.eval.EvalEngine) ID(org.matheclipse.core.expression.ID) IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) Set(java.util.Set) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) JSBuilder(org.matheclipse.core.form.output.JSBuilder) ISymbol(org.matheclipse.core.interfaces.ISymbol) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) MathMLUtilities(org.matheclipse.core.eval.MathMLUtilities) Logger(org.apache.logging.log4j.Logger) StringFunctions(org.matheclipse.core.builtin.StringFunctions) ExprParser(org.matheclipse.core.parser.ExprParser) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) StandardTokenizer(org.apache.lucene.analysis.standard.StandardTokenizer) TrieBuilder(org.matheclipse.parser.trie.TrieBuilder) IEvaluator(org.matheclipse.core.interfaces.IEvaluator) IFraction(org.matheclipse.core.interfaces.IFraction) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Encode(org.owasp.encoder.Encode) Message(org.apache.logging.log4j.message.Message) WriterOutputStream(org.matheclipse.core.eval.util.WriterOutputStream) Documentation(org.matheclipse.core.form.Documentation) TrieMatch(org.matheclipse.parser.trie.TrieMatch) Suppliers(com.google.common.base.Suppliers) FuzzyParser(org.matheclipse.api.parser.FuzzyParser) ThreadLocalNotifierClosable(org.matheclipse.logging.ThreadLocalNotifyingAppender.ThreadLocalNotifierClosable) SyntaxError(org.matheclipse.parser.client.SyntaxError) Soundex(org.apache.commons.codec.language.Soundex) PrintStream(java.io.PrintStream) CharTermAttribute(org.apache.lucene.analysis.tokenattributes.CharTermAttribute) TokenStream(org.apache.lucene.analysis.TokenStream) F(org.matheclipse.core.expression.F) IAST(org.matheclipse.core.interfaces.IAST) IBuiltInSymbol(org.matheclipse.core.interfaces.IBuiltInSymbol) StringWriter(java.io.StringWriter) PorterStemFilter(org.apache.lucene.analysis.en.PorterStemFilter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Config(org.matheclipse.core.basic.Config) GraphFunctions(org.matheclipse.core.builtin.GraphFunctions) IOException(java.io.IOException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) S(org.matheclipse.core.expression.S) StringReader(java.io.StringReader) ElementData1(org.matheclipse.core.data.ElementData1) TeXParser(org.matheclipse.core.form.tex.TeXParser) IExpr(org.matheclipse.core.interfaces.IExpr) Comparator(java.util.Comparator) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) RomanArabicConverter(com.baeldung.algorithms.romannumerals.RomanArabicConverter) WriterOutputStream(org.matheclipse.core.eval.util.WriterOutputStream) IBuiltInSymbol(org.matheclipse.core.interfaces.IBuiltInSymbol) StringWriter(java.io.StringWriter) SyntaxError(org.matheclipse.parser.client.SyntaxError) IInteger(org.matheclipse.core.interfaces.IInteger) EvalEngine(org.matheclipse.core.eval.EvalEngine) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) IAST(org.matheclipse.core.interfaces.IAST) IStringX(org.matheclipse.core.interfaces.IStringX) IDistribution(org.matheclipse.core.interfaces.IDistribution) IFraction(org.matheclipse.core.interfaces.IFraction) PrintStream(java.io.PrintStream) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ThreadLocalNotifierClosable(org.matheclipse.logging.ThreadLocalNotifyingAppender.ThreadLocalNotifierClosable) VariablesSet(org.matheclipse.core.convert.VariablesSet) ExprParser(org.matheclipse.core.parser.ExprParser) IEvaluator(org.matheclipse.core.interfaces.IEvaluator) IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 4 with StringUtils.replace

use of org.apache.commons.lang3.StringUtils.replace in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class ExperienceFragmentDataImpl method getLocalizedFragmentVariationPath.

/**
 * Returns the localized path of the experience fragment variation if the experience fragment resource is defined
 * in a template.
 *
 * @return Localized experience fragment variation path
 * @see ExperienceFragment#getLocalizedFragmentVariationPath()
 */
@Nullable
public String getLocalizedFragmentVariationPath() {
    if (localizedFragmentVariationPath != null) {
        return localizedFragmentVariationPath;
    }
    // get the configured fragment variation path
    String fragmentVariationPath = resource.getValueMap().get(ExperienceFragment.PN_FRAGMENT_VARIATION_PATH, String.class);
    if (currentPage != null && inTemplate()) {
        final Resource pageResource = Optional.ofNullable(currentPage).map(p -> p.adaptTo(Resource.class)).orElse(null);
        final String currentPageRootPath = pageResource != null ? LocalizationUtils.getLocalizationRoot(pageResource, resourceResolver, languageManager, relationshipManager) : null;
        // we should use getLocalizationRoot instead of getXfLocalizationRoot once the XF UI supports creating Live and Language Copies
        String xfRootPath = getXfLocalizationRoot(fragmentVariationPath, currentPageRootPath);
        if (StringUtils.isNotEmpty(currentPageRootPath) && StringUtils.isNotEmpty(xfRootPath)) {
            String xfRelativePath = StringUtils.substring(fragmentVariationPath, xfRootPath.length());
            String localizedXfRootPath = StringUtils.replace(currentPageRootPath, CONTENT_ROOT, ExperienceFragmentsConstants.CONTENT_PATH, 1);
            localizedFragmentVariationPath = StringUtils.join(localizedXfRootPath, xfRelativePath, PATH_DELIMITER_CHAR, NN_CONTENT);
        }
    }
    String xfContentPath = String.join(Character.toString(PATH_DELIMITER_CHAR), fragmentVariationPath, NN_CONTENT);
    if (!resourceExists(localizedFragmentVariationPath) && resourceExists(xfContentPath)) {
        localizedFragmentVariationPath = xfContentPath;
    }
    if (!isExperienceFragmentVariation(localizedFragmentVariationPath)) {
        localizedFragmentVariationPath = null;
    }
    return localizedFragmentVariationPath;
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) ExperienceFragmentsConstants(com.adobe.cq.xf.ExperienceFragmentsConstants) Resource(org.apache.sling.api.resource.Resource) ExperienceFragment(com.adobe.cq.wcm.core.components.models.ExperienceFragment) Text(com.day.text.Text) LanguageManager(com.day.cq.wcm.api.LanguageManager) NN_CONTENT(com.day.cq.wcm.api.NameConstants.NN_CONTENT) StringUtils(org.apache.commons.lang3.StringUtils) Page(com.day.cq.wcm.api.Page) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) LiveRelationshipManager(com.day.cq.wcm.msm.api.LiveRelationshipManager) LocalizationUtils(com.adobe.cq.wcm.core.components.util.LocalizationUtils) PageManager(com.day.cq.wcm.api.PageManager) Nullable(org.jetbrains.annotations.Nullable) ScriptVariable(org.apache.sling.models.annotations.injectorspecific.ScriptVariable) InjectionStrategy(org.apache.sling.models.annotations.injectorspecific.InjectionStrategy) Template(com.day.cq.wcm.api.Template) Model(org.apache.sling.models.annotations.Model) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) OSGiService(org.apache.sling.models.annotations.injectorspecific.OSGiService) SlingObject(org.apache.sling.models.annotations.injectorspecific.SlingObject) Resource(org.apache.sling.api.resource.Resource) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with StringUtils.replace

use of org.apache.commons.lang3.StringUtils.replace in project dhis2-core by dhis2.

the class TrackedEntityRegistrationSMSListener method postProcess.

// -------------------------------------------------------------------------
// IncomingSmsListener implementation
// -------------------------------------------------------------------------
@Override
protected void postProcess(IncomingSms sms, SMSCommand smsCommand, Map<String, String> parsedMessage) {
    String message = sms.getText();
    Date date = SmsUtils.lookForDate(message);
    String senderPhoneNumber = StringUtils.replace(sms.getOriginator(), "+", "");
    Collection<OrganisationUnit> orgUnits = getOrganisationUnits(sms);
    Program program = smsCommand.getProgram();
    OrganisationUnit orgUnit = SmsUtils.selectOrganisationUnit(orgUnits, parsedMessage, smsCommand);
    if (!programService.hasOrgUnit(program, orgUnit)) {
        sendFeedback(SMSCommand.NO_OU_FOR_PROGRAM, senderPhoneNumber, WARNING);
        throw new SMSParserException(SMSCommand.NO_OU_FOR_PROGRAM);
    }
    TrackedEntityInstance trackedEntityInstance = new TrackedEntityInstance();
    trackedEntityInstance.setOrganisationUnit(orgUnit);
    trackedEntityInstance.setTrackedEntityType(trackedEntityTypeService.getTrackedEntityByName(smsCommand.getProgram().getTrackedEntityType().getName()));
    Set<TrackedEntityAttributeValue> patientAttributeValues = new HashSet<>();
    smsCommand.getCodes().stream().filter(code -> parsedMessage.containsKey(code.getCode())).forEach(code -> {
        TrackedEntityAttributeValue trackedEntityAttributeValue = this.createTrackedEntityAttributeValue(parsedMessage, code, trackedEntityInstance);
        patientAttributeValues.add(trackedEntityAttributeValue);
    });
    long trackedEntityInstanceId = 0;
    if (patientAttributeValues.size() > 0) {
        trackedEntityInstanceId = trackedEntityInstanceService.createTrackedEntityInstance(trackedEntityInstance, patientAttributeValues);
    } else {
        sendFeedback("No TrackedEntityAttribute found", senderPhoneNumber, WARNING);
    }
    TrackedEntityInstance tei = trackedEntityInstanceService.getTrackedEntityInstance(trackedEntityInstanceId);
    programInstanceService.enrollTrackedEntityInstance(tei, smsCommand.getProgram(), new Date(), date, orgUnit);
    sendFeedback(StringUtils.defaultIfBlank(smsCommand.getSuccessMessage(), SUCCESS_MESSAGE + tei.getUid()), senderPhoneNumber, INFO);
    update(sms, SmsMessageStatus.PROCESSED, true);
}
Also used : MessageSender(org.hisp.dhis.message.MessageSender) CategoryService(org.hisp.dhis.category.CategoryService) TrackedEntityTypeService(org.hisp.dhis.trackedentity.TrackedEntityTypeService) Date(java.util.Date) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) StringUtils(org.apache.commons.lang3.StringUtils) Program(org.hisp.dhis.program.Program) HashSet(java.util.HashSet) ProgramStageInstanceService(org.hisp.dhis.program.ProgramStageInstanceService) SmsMessageStatus(org.hisp.dhis.sms.incoming.SmsMessageStatus) SMSParserException(org.hisp.dhis.sms.parse.SMSParserException) Map(java.util.Map) Qualifier(org.springframework.beans.factory.annotation.Qualifier) IncomingSmsService(org.hisp.dhis.sms.incoming.IncomingSmsService) ParserType(org.hisp.dhis.sms.parse.ParserType) SmsUtils(org.hisp.dhis.system.util.SmsUtils) UserService(org.hisp.dhis.user.UserService) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) Set(java.util.Set) IncomingSms(org.hisp.dhis.sms.incoming.IncomingSms) TrackedEntityInstanceService(org.hisp.dhis.trackedentity.TrackedEntityInstanceService) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) Component(org.springframework.stereotype.Component) SMSCommandService(org.hisp.dhis.sms.command.SMSCommandService) CurrentUserService(org.hisp.dhis.user.CurrentUserService) ProgramInstanceService(org.hisp.dhis.program.ProgramInstanceService) SMSCode(org.hisp.dhis.sms.command.code.SMSCode) ProgramService(org.hisp.dhis.program.ProgramService) SMSCommand(org.hisp.dhis.sms.command.SMSCommand) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) Transactional(org.springframework.transaction.annotation.Transactional) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) Program(org.hisp.dhis.program.Program) SMSParserException(org.hisp.dhis.sms.parse.SMSParserException) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) Date(java.util.Date) HashSet(java.util.HashSet)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)7 Map (java.util.Map)6 IOException (java.io.IOException)4 Set (java.util.Set)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 DatabaseTreeNode (com.kyj.fx.voeditor.visual.component.sql.dbtree.DatabaseTreeNode)2 DatabaseItemTree (com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.DatabaseItemTree)2 TableItemTree (com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.TableItemTree)2 SimpleTextView (com.kyj.fx.voeditor.visual.component.text.SimpleTextView)2 ConfigResourceLoader (com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader)2 ResourceLoader (com.kyj.fx.voeditor.visual.momory.ResourceLoader)2 DialogUtil (com.kyj.fx.voeditor.visual.util.DialogUtil)2 FxUtil (com.kyj.fx.voeditor.visual.util.FxUtil)2 ValueUtil (com.kyj.fx.voeditor.visual.util.ValueUtil)2 Collections (java.util.Collections)2 Date (java.util.Date)2 List (java.util.List)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2