Search in sources :

Example 1 with CommonsArrayList

use of com.helger.commons.collection.impl.CommonsArrayList in project ph-schematron by phax.

the class MainBenchmarkIsValidSchematron method main.

public static void main(final String[] args) {
    logSystemInfo();
    final ICommonsList<IReadableResource> aValidSchematrons = new CommonsArrayList<>();
    for (final IReadableResource aRes : SchematronTestHelper.getAllValidSchematronFiles()) if (!aRes.getPath().endsWith("/BIICORE-UBL-T01.sch") && !aRes.getPath().endsWith("/BIICORE-UBL-T10.sch") && !aRes.getPath().endsWith("/BIICORE-UBL-T14.sch") && !aRes.getPath().endsWith("/BIICORE-UBL-T15.sch") && !aRes.getPath().endsWith("/CellarBook.sch") && !aRes.getPath().endsWith("/pattern-example-with-includes.sch") && !aRes.getPath().endsWith("/pattern-example.sch") && !aRes.getPath().endsWith("/schematron-svrl.sch"))
        aValidSchematrons.add(aRes);
    s_aLogger.info("Starting");
    final double dTime1 = benchmarkTask(new ValidSchematronPure(aValidSchematrons));
    s_aLogger.info("Time pure: " + BigDecimal.valueOf(dTime1).toString() + " us");
    final double dTime2 = benchmarkTask(new ValidSchematronSCH(aValidSchematrons));
    s_aLogger.info("Time XSLT: " + BigDecimal.valueOf(dTime2).toString() + " us");
    s_aLogger.info("Time1 is " + BigDecimal.valueOf(dTime1 / dTime2 * 100).toString() + "% of time2");
}
Also used : IReadableResource(com.helger.commons.io.resource.IReadableResource) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Example 2 with CommonsArrayList

use of com.helger.commons.collection.impl.CommonsArrayList in project ph-css by phax.

the class MainFetchW3C_CSSTests method _fetch.

private static void _fetch(final String sURL, final String sDestDir) throws MalformedURLException {
    final ICommonsList<String> aCSSFilenames = new CommonsArrayList<>();
    System.out.println("Fetching from " + sURL);
    final ICommonsList<String> aIndex = StreamHelper.readStreamLines(new URLResource(sURL + "index.html"), StandardCharsets.UTF_8);
    {
        // Remove doctype
        aIndex.remove(0);
        // Fix HTML to be XML
        for (int i = 0; i < aIndex.size(); ++i) {
            final String sLine = aIndex.get(i);
            if (sLine.contains("<link"))
                aIndex.set(i, sLine + "</link>");
        }
    }
    final IMicroDocument aDoc = MicroReader.readMicroXML(StringHelper.getImploded('\n', aIndex));
    MicroVisitor.visit(aDoc, new DefaultHierarchyVisitorCallback<IMicroNode>() {

        @Override
        public EHierarchyVisitorReturn onItemBeforeChildren(final IMicroNode aItem) {
            if (aItem.isElement()) {
                final IMicroElement e = (IMicroElement) aItem;
                if (e.getTagName().equals("a")) {
                    final String sHref = e.getAttributeValue("href");
                    if (sHref.endsWith(".xml"))
                        aCSSFilenames.add(StringHelper.replaceAll(sHref, ".xml", ".css"));
                }
            }
            return EHierarchyVisitorReturn.CONTINUE;
        }
    });
    System.out.println("Fetching a total of " + aCSSFilenames.size() + " files");
    int i = 0;
    for (final String sCSSFilename : aCSSFilenames) {
        System.out.println("  " + (++i) + ".: " + sCSSFilename);
        final String sContent = StreamHelper.getAllBytesAsString(new URLResource(sURL + sCSSFilename), StandardCharsets.UTF_8);
        SimpleFileIO.writeFile(new File(sDestDir, sCSSFilename), sContent, StandardCharsets.UTF_8);
    }
}
Also used : URLResource(com.helger.commons.io.resource.URLResource) IMicroElement(com.helger.xml.microdom.IMicroElement) IMicroNode(com.helger.xml.microdom.IMicroNode) EHierarchyVisitorReturn(com.helger.commons.hierarchy.visit.EHierarchyVisitorReturn) IMicroDocument(com.helger.xml.microdom.IMicroDocument) File(java.io.File) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Example 3 with CommonsArrayList

use of com.helger.commons.collection.impl.CommonsArrayList in project ph-schematron by phax.

the class PSXPathBoundSchema method _createBoundPatterns.

/**
 * Pre-compile all patterns incl. their content
 *
 * @param aXPathContext
 * @param aXPathContext
 *        Global XPath object to use. May not be <code>null</code>.
 * @param aBoundDiagnostics
 *        A map from DiagnosticID to its mapped counterpart. May not be
 *        <code>null</code>.
 * @param aGlobalVariables
 *        The global Schematron-let variables. May not be <code>null</code>.
 * @return <code>null</code> if an XPath error is contained
 */
@Nullable
private ICommonsList<PSXPathBoundPattern> _createBoundPatterns(@Nonnull final XPath aXPathContext, @Nonnull final ICommonsMap<String, PSXPathBoundDiagnostic> aBoundDiagnostics, @Nonnull final IPSXPathVariables aGlobalVariables) {
    final ICommonsList<PSXPathBoundPattern> ret = new CommonsArrayList<>();
    boolean bHasAnyError = false;
    // For all relevant patterns
    for (final PSPattern aPattern : getAllRelevantPatterns()) {
        // Handle pattern specific variables
        final PSXPathVariables aPatternVariables = aGlobalVariables.getClone();
        if (aPattern.hasAnyLet()) {
            // map
            for (final Map.Entry<String, String> aEntry : aPattern.getAllLetsAsMap().entrySet()) if (aPatternVariables.add(aEntry).isUnchanged())
                error(aPattern, "Duplicate <let> with name '" + aEntry.getKey() + "' in <pattern>");
        }
        // For all rules of the current pattern
        final ICommonsList<PSXPathBoundRule> aBoundRules = new CommonsArrayList<>();
        for (final PSRule aRule : aPattern.getAllRules()) {
            // Handle rule specific variables
            final PSXPathVariables aRuleVariables = aPatternVariables.getClone();
            if (aRule.hasAnyLet()) {
                // variable map
                for (final Map.Entry<String, String> aEntry : aRule.getAllLetsAsMap().entrySet()) if (aRuleVariables.add(aEntry).isUnchanged())
                    error(aRule, "Duplicate <let> with name '" + aEntry.getKey() + "' in <rule>");
            }
            // For all contained assert and reports within the current rule
            final ICommonsList<PSXPathBoundAssertReport> aBoundAssertReports = new CommonsArrayList<>();
            for (final PSAssertReport aAssertReport : aRule.getAllAssertReports()) {
                final String sTest = aRuleVariables.getAppliedReplacement(aAssertReport.getTest());
                try {
                    final XPathExpression aTestExpr = _compileXPath(aXPathContext, sTest);
                    final ICommonsList<PSXPathBoundElement> aBoundElements = _createBoundElements(aAssertReport, aXPathContext, aRuleVariables);
                    if (aBoundElements == null) {
                        // Error already emitted
                        bHasAnyError = true;
                    } else {
                        final PSXPathBoundAssertReport aBoundAssertReport = new PSXPathBoundAssertReport(aAssertReport, sTest, aTestExpr, aBoundElements, aBoundDiagnostics);
                        aBoundAssertReports.add(aBoundAssertReport);
                    }
                } catch (final Throwable t) {
                    error(aAssertReport, "Failed to compile XPath expression in <" + (aAssertReport.isAssert() ? "assert" : "report") + ">: '" + sTest + "' with the following variables: " + aRuleVariables.getAll(), t);
                    bHasAnyError = true;
                }
            }
            // Evaluate base node set for this rule
            final String sRuleContext = aGlobalVariables.getAppliedReplacement(getValidationContext(aRule.getContext()));
            PSXPathBoundRule aBoundRule = null;
            try {
                final XPathExpression aRuleContext = _compileXPath(aXPathContext, sRuleContext);
                aBoundRule = new PSXPathBoundRule(aRule, sRuleContext, aRuleContext, aBoundAssertReports);
                aBoundRules.add(aBoundRule);
            } catch (final XPathExpressionException ex) {
                error(aRule, "Failed to compile XPath expression in <rule>: '" + sRuleContext + "'", ex.getCause() != null ? ex.getCause() : ex);
                bHasAnyError = true;
            }
        }
        // Create the bound pattern
        final PSXPathBoundPattern aBoundPattern = new PSXPathBoundPattern(aPattern, aBoundRules);
        ret.add(aBoundPattern);
    }
    if (bHasAnyError)
        return null;
    return ret;
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) PSRule(com.helger.schematron.pure.model.PSRule) XPathExpressionException(javax.xml.xpath.XPathExpressionException) PSXPathVariables(com.helger.schematron.pure.binding.xpath.PSXPathVariables) IPSXPathVariables(com.helger.schematron.pure.binding.xpath.IPSXPathVariables) PSAssertReport(com.helger.schematron.pure.model.PSAssertReport) PSPattern(com.helger.schematron.pure.model.PSPattern) Map(java.util.Map) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) Nullable(javax.annotation.Nullable)

Example 4 with CommonsArrayList

use of com.helger.commons.collection.impl.CommonsArrayList in project ph-css by phax.

the class CSSShortHandDescriptor method getSplitIntoPieces.

@Nonnull
@ReturnsMutableCopy
public ICommonsList<CSSDeclaration> getSplitIntoPieces(@Nonnull final CSSDeclaration aDeclaration) {
    ValueEnforcer.notNull(aDeclaration, "Declaration");
    // Check that declaration matches this property
    if (!aDeclaration.hasProperty(m_eProperty))
        throw new IllegalArgumentException("Cannot split a '" + aDeclaration.getProperty() + "' as a '" + m_eProperty.getName() + "'");
    // global
    final int nSubProperties = m_aSubProperties.size();
    final ICommonsList<CSSDeclaration> ret = new CommonsArrayList<>();
    final ICommonsList<ICSSExpressionMember> aExpressionMembers = aDeclaration.getExpression().getAllMembers();
    // Modification for margin and padding
    modifyExpressionMembers(aExpressionMembers);
    final int nExpressionMembers = aExpressionMembers.size();
    final CSSWriterSettings aCWS = new CSSWriterSettings(ECSSVersion.CSS30, false);
    final boolean[] aHandledSubProperties = new boolean[nSubProperties];
    // For all expression members
    for (int nExprMemberIndex = 0; nExprMemberIndex < nExpressionMembers; ++nExprMemberIndex) {
        final ICSSExpressionMember aMember = aExpressionMembers.get(nExprMemberIndex);
        // For all unhandled sub-properties
        for (int nSubPropIndex = 0; nSubPropIndex < nSubProperties; ++nSubPropIndex) if (!aHandledSubProperties[nSubPropIndex]) {
            final CSSPropertyWithDefaultValue aSubProp = m_aSubProperties.get(nSubPropIndex);
            final ICSSProperty aProperty = aSubProp.getProperty();
            final int nMinArgs = aProperty.getMinimumArgumentCount();
            // Always use minimum number of arguments
            if (nExprMemberIndex + nMinArgs - 1 < nExpressionMembers) {
                // Build sum of all members
                final StringBuilder aSB = new StringBuilder();
                for (int k = 0; k < nMinArgs; ++k) {
                    final String sValue = aMember.getAsCSSString(aCWS);
                    if (aSB.length() > 0)
                        aSB.append(' ');
                    aSB.append(sValue);
                }
                if (aProperty.isValidValue(aSB.toString())) {
                    // We found a match
                    final CSSExpression aExpr = new CSSExpression();
                    for (int k = 0; k < nMinArgs; ++k) aExpr.addMember(aExpressionMembers.get(nExprMemberIndex + k));
                    ret.add(new CSSDeclaration(aSubProp.getProperty().getPropertyName(), aExpr));
                    nExprMemberIndex += nMinArgs - 1;
                    // Remember as handled
                    aHandledSubProperties[nSubPropIndex] = true;
                    // Next expression member
                    break;
                }
            }
        }
    }
    // Assign all default values that are not present
    for (int nSubPropIndex = 0; nSubPropIndex < nSubProperties; ++nSubPropIndex) if (!aHandledSubProperties[nSubPropIndex]) {
        final CSSPropertyWithDefaultValue aSubProp = m_aSubProperties.get(nSubPropIndex);
        // assign default value
        final CSSExpression aExpr = new CSSExpression();
        aExpr.addMember(new CSSExpressionMemberTermSimple(aSubProp.getDefaultValue()));
        ret.add(new CSSDeclaration(aSubProp.getProperty().getPropertyName(), aExpr));
    }
    return ret;
}
Also used : ICSSProperty(com.helger.css.property.ICSSProperty) CSSExpressionMemberTermSimple(com.helger.css.decl.CSSExpressionMemberTermSimple) ICSSExpressionMember(com.helger.css.decl.ICSSExpressionMember) CSSExpression(com.helger.css.decl.CSSExpression) CSSWriterSettings(com.helger.css.writer.CSSWriterSettings) CSSDeclaration(com.helger.css.decl.CSSDeclaration) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull)

Example 5 with CommonsArrayList

use of com.helger.commons.collection.impl.CommonsArrayList in project as2-server by phax.

the class SocketCommandProcessor method processCommand.

@Override
public void processCommand() throws OpenAS2Exception {
    try (final SSLSocket socket = (SSLSocket) m_aSSLServerSocket.accept()) {
        socket.setSoTimeout(2000);
        m_aReader = new NonBlockingBufferedReader(new InputStreamReader(socket.getInputStream()));
        m_aWriter = new NonBlockingBufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        final String line = m_aReader.readLine();
        m_aParser.parse(line);
        if (!m_aParser.getUserid().equals(m_sUserID)) {
            m_aWriter.write("Bad userid/password");
            throw new OpenAS2Exception("Bad userid");
        }
        if (!m_aParser.getPassword().equals(m_sPassword)) {
            m_aWriter.write("Bad userid/password");
            throw new OpenAS2Exception("Bad password");
        }
        final String str = m_aParser.getCommandText();
        if (str != null && str.length() > 0) {
            final CommandTokenizer cmdTkn = new CommandTokenizer(str);
            if (cmdTkn.hasMoreTokens()) {
                final String sCommandName = cmdTkn.nextToken().toLowerCase();
                if (sCommandName.equals(StreamCommandProcessor.EXIT_COMMAND)) {
                    terminate();
                } else {
                    final ICommonsList<String> params = new CommonsArrayList<>();
                    while (cmdTkn.hasMoreTokens()) {
                        params.add(cmdTkn.nextToken());
                    }
                    final ICommand aCommand = getCommand(sCommandName);
                    if (aCommand != null) {
                        final CommandResult aResult = aCommand.execute(params.toArray());
                        if (aResult.getType().isSuccess()) {
                            m_aWriter.write(aResult.getAsXMLString());
                        } else {
                            m_aWriter.write("\r\n" + StreamCommandProcessor.COMMAND_ERROR + "\r\n");
                            m_aWriter.write(aResult.getResultAsString());
                        }
                    } else {
                        m_aWriter.write(StreamCommandProcessor.COMMAND_NOT_FOUND + "> " + sCommandName + "\r\n");
                        m_aWriter.write("List of commands:" + "\r\n");
                        for (final String sCurCmd : getAllCommands().keySet()) m_aWriter.write(sCurCmd + "\r\n");
                    }
                }
            }
        }
        m_aWriter.flush();
    } catch (final Exception ex) {
        throw WrappedOpenAS2Exception.wrap(ex);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) SSLSocket(javax.net.ssl.SSLSocket) NonBlockingBufferedWriter(com.helger.commons.io.stream.NonBlockingBufferedWriter) IOException(java.io.IOException) OpenAS2Exception(com.helger.as2lib.exception.OpenAS2Exception) WrappedOpenAS2Exception(com.helger.as2lib.exception.WrappedOpenAS2Exception) CommandResult(com.helger.as2.cmd.CommandResult) OpenAS2Exception(com.helger.as2lib.exception.OpenAS2Exception) WrappedOpenAS2Exception(com.helger.as2lib.exception.WrappedOpenAS2Exception) CommandTokenizer(com.helger.as2.util.CommandTokenizer) ICommand(com.helger.as2.cmd.ICommand) OutputStreamWriter(java.io.OutputStreamWriter) NonBlockingBufferedReader(com.helger.commons.io.stream.NonBlockingBufferedReader) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Aggregations

CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)13 Nullable (javax.annotation.Nullable)6 Nonnull (javax.annotation.Nonnull)5 ICommonsList (com.helger.commons.collection.impl.ICommonsList)4 ValueEnforcer (com.helger.commons.ValueEnforcer)3 Nonempty (com.helger.commons.annotation.Nonempty)3 CSSNode (com.helger.css.parser.CSSNode)3 File (java.io.File)3 CommandResult (com.helger.as2.cmd.CommandResult)2 ICommand (com.helger.as2.cmd.ICommand)2 CommandTokenizer (com.helger.as2.util.CommandTokenizer)2 CommonsHashMap (com.helger.commons.collection.impl.CommonsHashMap)2 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)2 IReadableResource (com.helger.commons.io.resource.IReadableResource)2 StringHelper (com.helger.commons.string.StringHelper)2 ECSSVersion (com.helger.css.ECSSVersion)2 com.helger.css.decl (com.helger.css.decl)2 EModifier (com.helger.css.decl.CSSMediaQuery.EModifier)2 ECSSMediaExpressionFeature (com.helger.css.media.ECSSMediaExpressionFeature)2 ECSSMedium (com.helger.css.media.ECSSMedium)2