Search in sources :

Example 6 with CommonsArrayList

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

the class StreamCommandProcessor method processCommand.

@Override
public void processCommand() throws OpenAS2Exception {
    try {
        final String sLine = readLine();
        if (sLine != null) {
            final CommandTokenizer aTokenizer = new CommandTokenizer(sLine);
            if (aTokenizer.hasMoreTokens()) {
                final String sCommandName = aTokenizer.nextToken().toLowerCase(Locale.US);
                if (sCommandName.equals(EXIT_COMMAND)) {
                    terminate();
                } else {
                    final ICommonsList<String> aParams = new CommonsArrayList<>();
                    while (aTokenizer.hasMoreTokens()) {
                        aParams.add(aTokenizer.nextToken());
                    }
                    final ICommand aCommand = getCommand(sCommandName);
                    if (aCommand != null) {
                        final CommandResult aResult = aCommand.execute(aParams.toArray());
                        if (aResult.getType().isSuccess()) {
                            writeLine(aResult.toString());
                        } else {
                            writeLine(COMMAND_ERROR);
                            writeLine(aResult.getResultAsString());
                        }
                    } else {
                        writeLine(COMMAND_NOT_FOUND + "> " + sCommandName);
                        writeLine("List of commands:");
                        writeLine(EXIT_COMMAND);
                        for (final String sCurCmd : getAllCommands().keySet()) writeLine(sCurCmd);
                    }
                }
            }
            write(PROMPT);
        } else {
            ThreadHelper.sleep(100);
        }
    } catch (final IOException ex) {
        throw WrappedOpenAS2Exception.wrap(ex);
    }
}
Also used : CommandTokenizer(com.helger.as2.util.CommandTokenizer) ICommand(com.helger.as2.cmd.ICommand) IOException(java.io.IOException) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) CommandResult(com.helger.as2.cmd.CommandResult)

Example 7 with CommonsArrayList

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

the class Schematron method _performValidation.

private void _performValidation(@Nonnull final ISchematronResource aSch, @Nonnull final ICommonsList<ResourceCollection> aResCollections, @Nullable final File aSVRLDirectory, final boolean bExpectSuccess) throws BuildException {
    // Resolve resourceCollections - pain in the ass
    final ICommonsMap<File, DirectoryData> aFiles = new CommonsHashMap<>();
    for (final ResourceCollection aResCollection : aResCollections) {
        if (!aResCollection.isFilesystemOnly())
            _error("Only FileSystem resources are supported.");
        else
            for (final Resource aRes : aResCollection) {
                if (!aRes.isExists()) {
                    _error("Could not find resource " + aRes.toLongString() + " to copy.");
                    continue;
                }
                File baseDir = NULL_FILE_PLACEHOLDER;
                String name = aRes.getName();
                final FileProvider fp = aRes.as(FileProvider.class);
                if (fp != null) {
                    final FileResource fr = ResourceUtils.asFileResource(fp);
                    baseDir = _getKeyFile(fr.getBaseDir());
                    if (baseDir == NULL_FILE_PLACEHOLDER)
                        name = fr.getFile().getAbsolutePath();
                }
                if ((aRes.isDirectory() || fp != null) && name != null) {
                    final DirectoryData aBaseDir = aFiles.computeIfAbsent(_getKeyFile(baseDir), k -> new DirectoryData(k));
                    if (aRes.isDirectory())
                        aBaseDir.addDir(name);
                    else
                        aBaseDir.addFile(name);
                } else
                    _error("Could not resolve resource " + aRes.toLongString() + " to a file.");
            }
    }
    for (final DirectoryData aBaseDir : aFiles.values()) {
        log("Scanning directory " + aBaseDir.getBaseDir() + " for XMLs to be Schematron validated", Project.MSG_DEBUG);
        final ICommonsList<String> aIncludes = new CommonsArrayList<>();
        aIncludes.addAll(aBaseDir.getFiles());
        for (final String sFile : aBaseDir.getDirs()) aIncludes.add(sFile + "/**");
        final DirectoryScanner aScanner = new DirectoryScanner();
        aScanner.setBasedir(aBaseDir.getBaseDir());
        if (aIncludes.isNotEmpty())
            aScanner.setIncludes(aIncludes.toArray(new String[0]));
        aScanner.setCaseSensitive(true);
        aScanner.scan();
        final String[] aXMLFilenames = aScanner.getIncludedFiles();
        if (aXMLFilenames != null) {
            for (final String sXMLFilename : aXMLFilenames) {
                final File aXMLFile = new File(aBaseDir.getBaseDir(), sXMLFilename);
                // Validate XML file
                log("Validating XML file '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile.getName() + "' expecting " + (bExpectSuccess ? "success" : "failure"), Project.MSG_INFO);
                try {
                    final SchematronOutputType aSOT = aSch.applySchematronValidationToSVRL(TransformSourceFactory.create(aXMLFile));
                    if (aSVRLDirectory != null) {
                        // Save SVRL
                        final File aSVRLFile = new File(aSVRLDirectory, sXMLFilename + ".svrl");
                        if (!aSVRLFile.getParentFile().mkdirs())
                            log("Failed to create parent directory of '" + aSVRLFile.getAbsolutePath() + "'!", Project.MSG_ERR);
                        if (new SVRLMarshaller().write(aSOT, aSVRLFile).isSuccess())
                            log("Successfully saved SVRL file '" + aSVRLFile.getPath() + "'", Project.MSG_INFO);
                        else
                            log("Error saving SVRL file '" + aSVRLFile.getPath() + "'", Project.MSG_ERR);
                    }
                    if (false)
                        System.out.println(new SVRLMarshaller().getAsString(aSOT));
                    final ICommonsList<AbstractSVRLMessage> aMessages = SVRLHelper.getAllFailedAssertionsAndSuccessfulReports(aSOT);
                    final int nErrorMessages = aMessages.getCount(x -> x.getFlag().isError());
                    final int nWarningMessages = aMessages.size() - nErrorMessages;
                    final String sErrors = nErrorMessages + " Schematron error" + (nErrorMessages == 1 ? "" : "s");
                    final String sWarnings = nWarningMessages + " Schematron warning" + (nWarningMessages == 1 ? "" : "s");
                    if (bExpectSuccess) {
                        // No failed assertions expected
                        if (nErrorMessages > 0) {
                            final StringBuilder aMessage = new StringBuilder();
                            aMessage.append(sErrors + (nWarningMessages > 0 ? " and " + sWarnings : "") + " for XML file '" + aXMLFile.getPath() + "'");
                            for (final AbstractSVRLMessage aMsg : aMessages) {
                                aMessage.append("\n  ").append(ErrorTextProvider.DEFAULT.getErrorText(aMsg.getAsResourceError(aXMLFile.getPath()), Locale.US));
                            }
                            // As at least one error is contained, it's okay to throw an
                            // exception in case
                            _error(aMessage.toString());
                            continue;
                        }
                        // Success as expected
                        log("XML file '" + aXMLFile.getPath() + "' was validated against Schematron '" + aSch.getResource().getPath() + "' and matches the rules" + (nWarningMessages > 0 ? " - only " + sWarnings + " are contained" : ""), Project.MSG_INFO);
                    } else {
                        // At least one failed assertions expected
                        if (nErrorMessages == 0) {
                            String sMessage = "No Schematron errors for erroneous XML file '" + aXMLFile.getPath() + "'";
                            if (nWarningMessages > 0)
                                sMessage += " - only " + sWarnings + " are contained";
                            _error(sMessage);
                            continue;
                        }
                        // Success as expected
                        log("XML file '" + aXMLFile.getPath() + "' was validated against Schematron '" + aSch.getResource().getPath() + "' " + sErrors + (nWarningMessages > 0 ? " and " + sWarnings : "") + " were found (as expected)", Project.MSG_INFO);
                    }
                } catch (final BuildException up) {
                    throw up;
                } catch (final Exception ex) {
                    final String sMessage = "Exception validating XML '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile.getName() + "'. Technical details: " + ex.getClass().getSimpleName() + " - " + ex.getMessage();
                    _error(sMessage, ex);
                    continue;
                }
            }
        }
    }
}
Also used : OverrideOnDemand(com.helger.commons.annotation.OverrideOnDemand) Task(org.apache.tools.ant.Task) IError(com.helger.commons.error.IError) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) URIResolver(javax.xml.transform.URIResolver) ResourceCollection(org.apache.tools.ant.types.ResourceCollection) FileResource(org.apache.tools.ant.types.resources.FileResource) SchematronResourceXSLT(com.helger.schematron.xslt.SchematronResourceXSLT) AbstractSVRLMessage(com.helger.schematron.svrl.AbstractSVRLMessage) SVRLHelper(com.helger.schematron.svrl.SVRLHelper) ESchematronMode(com.helger.schematron.ESchematronMode) Locale(java.util.Locale) Project(org.apache.tools.ant.Project) CollectingTransformErrorListener(com.helger.xml.transform.CollectingTransformErrorListener) Nonnull(javax.annotation.Nonnull) TransformSourceFactory(com.helger.xml.transform.TransformSourceFactory) Nullable(javax.annotation.Nullable) EntityResolver(org.xml.sax.EntityResolver) ErrorTextProvider(com.helger.commons.error.ErrorTextProvider) Resource(org.apache.tools.ant.types.Resource) EErrorLevel(com.helger.commons.error.level.EErrorLevel) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) StringHelper(com.helger.commons.string.StringHelper) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) CollectingPSErrorHandler(com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler) BuildException(org.apache.tools.ant.BuildException) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) File(java.io.File) SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) XMLCatalog(org.apache.tools.ant.types.XMLCatalog) ISchematronResource(com.helger.schematron.ISchematronResource) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsList(com.helger.commons.collection.impl.ICommonsList) SchematronResourceSCH(com.helger.schematron.xslt.SchematronResourceSCH) FileProvider(org.apache.tools.ant.types.resources.FileProvider) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) IErrorList(com.helger.commons.error.list.IErrorList) ResourceUtils(org.apache.tools.ant.util.ResourceUtils) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) ISchematronResource(com.helger.schematron.ISchematronResource) FileResource(org.apache.tools.ant.types.resources.FileResource) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) AbstractSVRLMessage(com.helger.schematron.svrl.AbstractSVRLMessage) BuildException(org.apache.tools.ant.BuildException) SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) FileProvider(org.apache.tools.ant.types.resources.FileProvider) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) ResourceCollection(org.apache.tools.ant.types.ResourceCollection)

Example 8 with CommonsArrayList

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

the class SchematronTestHelper method _readDI.

@Nonnull
private static ICommonsList<SchematronTestFile> _readDI(@Nonnull final IReadableResource aRes) {
    if (false)
        ClassPathHelper.getAllClassPathEntries().forEach(x -> {
            System.out.println(x);
            if (new File(x).isDirectory()) {
                final FileSystemRecursiveIterator it = new FileSystemRecursiveIterator(new File(x));
                it.forEach(y -> System.out.println(StringHelper.getRepeated("  ", it.getLevel()) + y));
            }
        });
    ValueEnforcer.notNull(aRes, "Resource");
    ValueEnforcer.isTrue(aRes.exists(), () -> "Resource " + aRes + " does not exist!");
    final ICommonsList<SchematronTestFile> ret = new CommonsArrayList<>();
    final IMicroDocument aDoc = MicroReader.readMicroXML(aRes);
    if (aDoc == null)
        throw new IllegalArgumentException("Failed to open/parse " + aRes + " as XML");
    String sLastParentDirBaseName = null;
    for (final IMicroElement eItem : aDoc.getDocumentElement().getAllChildElements()) if (eItem.getTagName().equals("directory"))
        sLastParentDirBaseName = eItem.getAttributeValue("basename");
    else if (eItem.getTagName().equals("file"))
        ret.add(new SchematronTestFile(sLastParentDirBaseName, new ClassPathResource(eItem.getAttributeValue("name")), eItem.getAttributeValue("basename")));
    else
        throw new IllegalArgumentException("Cannot handle " + eItem);
    return ret;
}
Also used : CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) ClassPathHelper(com.helger.commons.lang.ClassPathHelper) StringHelper(com.helger.commons.string.StringHelper) IReadableResource(com.helger.commons.io.resource.IReadableResource) IMicroDocument(com.helger.xml.microdom.IMicroDocument) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) File(java.io.File) ValueEnforcer(com.helger.commons.ValueEnforcer) FileSystemRecursiveIterator(com.helger.commons.io.file.FileSystemRecursiveIterator) ICommonsList(com.helger.commons.collection.impl.ICommonsList) Nonempty(com.helger.commons.annotation.Nonempty) IMicroElement(com.helger.xml.microdom.IMicroElement) MicroReader(com.helger.xml.microdom.serialize.MicroReader) Nonnull(javax.annotation.Nonnull) FileSystemRecursiveIterator(com.helger.commons.io.file.FileSystemRecursiveIterator) IMicroElement(com.helger.xml.microdom.IMicroElement) IMicroDocument(com.helger.xml.microdom.IMicroDocument) File(java.io.File) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) Nonnull(javax.annotation.Nonnull)

Example 9 with CommonsArrayList

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

the class PSXPathBoundSchema method _createBoundElements.

@Nullable
private ICommonsList<PSXPathBoundElement> _createBoundElements(@Nonnull final IPSHasMixedContent aMixedContent, @Nonnull final XPath aXPathContext, @Nonnull final IPSXPathVariables aVariables) {
    final ICommonsList<PSXPathBoundElement> ret = new CommonsArrayList<>();
    boolean bHasAnyError = false;
    for (final Object aContentElement : aMixedContent.getAllContentElements()) {
        if (aContentElement instanceof PSName) {
            final PSName aName = (PSName) aContentElement;
            if (aName.hasPath()) {
                // Replace all variables
                final String sPath = aVariables.getAppliedReplacement(aName.getPath());
                try {
                    final XPathExpression aXpathExpression = _compileXPath(aXPathContext, sPath);
                    ret.add(new PSXPathBoundElement(aName, sPath, aXpathExpression));
                } catch (final XPathExpressionException ex) {
                    error(aName, "Failed to compile XPath expression in <name>: '" + sPath + "'", ex.getCause() != null ? ex.getCause() : ex);
                    bHasAnyError = true;
                }
            } else {
                // No XPath required
                ret.add(new PSXPathBoundElement(aName));
            }
        } else if (aContentElement instanceof PSValueOf) {
            final PSValueOf aValueOf = (PSValueOf) aContentElement;
            // Replace variables
            final String sSelect = aVariables.getAppliedReplacement(aValueOf.getSelect());
            try {
                final XPathExpression aXPathExpression = _compileXPath(aXPathContext, sSelect);
                ret.add(new PSXPathBoundElement(aValueOf, sSelect, aXPathExpression));
            } catch (final XPathExpressionException ex) {
                error(aValueOf, "Failed to compile XPath expression in <value-of>: '" + sSelect + "'", ex);
                bHasAnyError = true;
            }
        } else {
            // No XPath compilation necessary
            if (aContentElement instanceof String)
                ret.add(new PSXPathBoundElement((String) aContentElement));
            else
                ret.add(new PSXPathBoundElement((IPSElement) aContentElement));
        }
    }
    if (bHasAnyError)
        return null;
    return ret;
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) IPSElement(com.helger.schematron.pure.model.IPSElement) PSName(com.helger.schematron.pure.model.PSName) XPathExpressionException(javax.xml.xpath.XPathExpressionException) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) PSValueOf(com.helger.schematron.pure.model.PSValueOf) Nullable(javax.annotation.Nullable)

Example 10 with CommonsArrayList

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

the class CSSNodeToDomainObject method _createPageRule.

@Nonnull
@SuppressFBWarnings("IL_INFINITE_LOOP")
private CSSPageRule _createPageRule(@Nonnull final CSSNode aNode) {
    _expectNodeType(aNode, ECSSNodeType.PAGERULE);
    final int nChildCount = aNode.jjtGetNumChildren();
    if (m_eVersion == ECSSVersion.CSS30) {
        if (nChildCount < 1)
            _throwUnexpectedChildrenCount(aNode, "Expected at least 1 child but got " + nChildCount + "!");
        // Read page selectors (0-n)
        final ICommonsList<String> aSelectors = new CommonsArrayList<>();
        for (int nIndex = 0; nIndex < nChildCount - 1; ++nIndex) {
            final CSSNode aChildNode = aNode.jjtGetChild(nIndex);
            _expectNodeType(aChildNode, ECSSNodeType.PAGESELECTOR);
            aSelectors.add(aChildNode.getText());
        }
        final CSSPageRule ret = new CSSPageRule(aSelectors);
        ret.setSourceLocation(aNode.getSourceLocation());
        // Read page body
        final CSSNode aBodyNode = aNode.jjtGetChild(nChildCount - 1);
        _expectNodeType(aBodyNode, ECSSNodeType.PAGERULEBLOCK);
        final int nBodyChildren = aBodyNode.jjtGetNumChildren();
        for (int nIndex = 0; nIndex < nBodyChildren; ++nIndex) {
            final CSSNode aBodyChildNode = aBodyNode.jjtGetChild(nIndex);
            if (ECSSNodeType.STYLEDECLARATION.isNode(aBodyChildNode, m_eVersion)) {
                final CSSDeclaration aDeclaration = _createDeclaration(aBodyChildNode);
                if (aDeclaration != null)
                    ret.addMember(aDeclaration);
            } else if (ECSSNodeType.PAGEMARGINSYMBOL.isNode(aBodyChildNode, m_eVersion)) {
                final CSSPageMarginBlock aBlock = new CSSPageMarginBlock(aBodyChildNode.getText());
                final CSSNode aBodyNextChildNode = aBodyNode.jjtGetChild(nIndex + 1);
                _readStyleDeclarationList(aBodyNextChildNode, aDeclaration -> aBlock.addDeclaration(aDeclaration));
                ret.addMember(aBlock);
                // Skip style declaration list
                ++nIndex;
            } else if (!ECSSNodeType.isErrorNode(aBodyChildNode, m_eVersion))
                m_aErrorHandler.onCSSInterpretationError("Unsupported page rule body child: " + ECSSNodeType.getNodeName(aBodyChildNode, m_eVersion));
        }
        return ret;
    }
    String sPseudoPage = null;
    int nStartIndex = 0;
    if (nChildCount > 0) {
        final CSSNode aFirstChild = aNode.jjtGetChild(0);
        if (ECSSNodeType.PSEUDOPAGE.isNode(aFirstChild, m_eVersion)) {
            sPseudoPage = aFirstChild.getText();
            nStartIndex++;
        }
    }
    final CSSPageRule ret = new CSSPageRule(sPseudoPage);
    ret.setSourceLocation(aNode.getSourceLocation());
    for (int nIndex = nStartIndex; nIndex < nChildCount; ++nIndex) {
        final CSSNode aChildNode = aNode.jjtGetChild(nIndex);
        if (ECSSNodeType.STYLEDECLARATIONLIST.isNode(aChildNode, m_eVersion)) {
            // Read all contained declarations
            _readStyleDeclarationList(aChildNode, aDeclaration -> ret.addMember(aDeclaration));
        } else if (!ECSSNodeType.isErrorNode(aChildNode, m_eVersion))
            m_aErrorHandler.onCSSInterpretationError("Unsupported page rule child: " + ECSSNodeType.getNodeName(aChildNode, m_eVersion));
    }
    return ret;
}
Also used : ICSSInterpretErrorHandler(com.helger.css.reader.errorhandler.ICSSInterpretErrorHandler) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) ECSSMedium(com.helger.css.media.ECSSMedium) CSSParseHelper(com.helger.css.parser.CSSParseHelper) ECSSVersion(com.helger.css.ECSSVersion) ValueEnforcer(com.helger.commons.ValueEnforcer) Consumer(java.util.function.Consumer) com.helger.css.decl(com.helger.css.decl) CSSNode(com.helger.css.parser.CSSNode) ICommonsList(com.helger.commons.collection.impl.ICommonsList) Nonempty(com.helger.commons.annotation.Nonempty) ECSSMediaExpressionFeature(com.helger.css.media.ECSSMediaExpressionFeature) Nonnull(javax.annotation.Nonnull) EModifier(com.helger.css.decl.CSSMediaQuery.EModifier) Nullable(javax.annotation.Nullable) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) CSSNode(com.helger.css.parser.CSSNode) Nonnull(javax.annotation.Nonnull) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

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