Example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

List of usage examples for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

Introduction

In this page you can find the example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Prototype

String W3C_XML_SCHEMA_NS_URI

To view the source code for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Click Source Link

Document

W3C XML Schema Namespace URI.

Usage

From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public ProfileServiceImpl(TypedProfileDAO profileDAO, ProfiledItemTypeDAO profiledItemTypeDAO,
        String docBuilderFactory) {

    this.typedProfileDAO = profileDAO;
    this.profiledItemTypeDAO = profiledItemTypeDAO;
    if (docBuilderFactory != null)
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", docBuilderFactory);
    dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//w w w  .j  a  v  a2  s.c o  m
    sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    if (logger.isDebugEnabled()) {
        logger.debug("DocumentBuilderFactory: " + dbf.getClass().getName());
        ClassLoader cl = Thread.currentThread().getContextClassLoader().getSystemClassLoader();
        URL url = cl.getResource("org/apache/xerces/jaxp/DocumentBuilderFactoryImpl.class");
        logger.debug("Parser loaded from: " + url);
    }
    validationParsers = new HashMap<Integer, Map<String, DocumentBuilder>>();

    loadSchemas();
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (Exception e) {

    }
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.util.ErrorLibraryUtils.java

public static boolean validateAgainstSchema(String xmlLocation, String xsdLocation)
        throws PreProcessFailedException {
    boolean isValidate = false;

    Document document = null;// www.  ja v  a2 s . com
    Schema schema = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder parser = domFactory.newDocumentBuilder();
        document = parser.parse(new File(xmlLocation));

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = Thread.currentThread().getContextClassLoader().getResource(xsdLocation);
        if (schemaUrl == null) {
            throw new PreProcessFailedException("Unable to find schema resource: " + xsdLocation);
        }

        InputStream stream = null;
        try {
            stream = schemaUrl.openStream();
            Source schemaFile = new StreamSource(stream);
            schema = factory.newSchema(schemaFile);
        } finally {
            IOUtils.closeQuietly(stream);
        }

    } catch (ParserConfigurationException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "XML parsing failed because of IOException : " + exception.getMessage(), exception);
    } catch (Exception exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);
    }

    Validator validator = schema.newValidator();

    try {
        validator.validate(new DOMSource(document));
        isValidate = true;
    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML validation against XSD failed : " + exception.getMessage(),
                exception);
    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "Schema validation failed because of IOException : " + exception.getMessage(), exception);
    }

    return isValidate;
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

public static void validate(IPath tmpFileInWorkspaceDir)
        throws IOException, ParserConfigurationException, SAXException, URISyntaxException {

    // TODO delete commented out code which was used for debugging (debug code needs to stay at least two releases after 2.5.9)
    // Get the XSD file
    Bundle bundle = Platform.getBundle("org.eclipse.mdht.dita.ui");
    // Path ditaSchemadirPath = new Path("DITA-OT/schema/technicalContent/xsd/topic.xsd");
    // URL ditaXSD = FileLocator.toFileURL(FileLocator.find(bundle, ditaSchemadirPath, null));
    Path ditaFolderPath = new Path("DITA-OT");
    URL ditaFolder = FileLocator.toFileURL(FileLocator.find(bundle, ditaFolderPath, null));
    // System.out.println(ditaFolder);

    // Create DBF and ignore DTD
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//w ww.  java  2  s.  c o m
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document document = parser.parse(tmpFileInWorkspaceDir.toFile());

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Use catalog
    // Path ditaCatalogPath = new Path("DITA-OT/schema/catalog.xml");
    // URL ditaCatalog = FileLocator.toFileURL(FileLocator.find(bundle, ditaCatalogPath, null));
    File ditaCatalogFile = new File(ditaFolder.getFile(), "schema/catalog.xml");
    // System.out.println(ditaCatalogFile);
    // System.out.println(ditaCatalogFile.exists());
    XMLCatalogResolver resolver = new XMLCatalogResolver(new String[] { ditaCatalogFile.getAbsolutePath() });
    schemaFactory.setResourceResolver(resolver);

    // load a WXS schema, represented by a Schema instance
    File ditaSchemaFile = new File(ditaFolder.getFile(), "schema/technicalContent/xsd/topic.xsd");

    // System.out.println(ditaSchemaFile);
    // System.out.println(ditaSchemaFile.exists());
    Source schemaFile = new StreamSource(ditaSchemaFile);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();

    DOMSource dom = new DOMSource(document);
    validator.validate(dom);
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.DescriptionHelper.java

/**
 * Validates <code>*.wbp-component.xml</code> against its schema.
 *///from w w  w .  j a va 2s.  c  o  m
public static synchronized void validateComponentDescription(ResourceInfo resource) throws Exception {
    // validate on developers computers
    if (EnvironmentUtils.isTestingTime()) {
        // prepare Schema
        if (m_wbpComponentSchema == null) {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            InputStream schemaStream = DesignerPlugin.getFile("schema/wbp-component.xsd");
            m_wbpComponentSchema = factory.newSchema(new StreamSource(schemaStream));
        }
        // validate
        InputStream contents = resource.getURL().openStream();
        try {
            Validator validator = m_wbpComponentSchema.newValidator();
            validator.validate(new StreamSource(contents));
        } catch (Throwable e) {
            throw new Exception("Exception during validation " + resource.getURL(), e);
        } finally {
            contents.close();
        }
    }
}

From source file:org.eclipse.winery.common.ModelUtilities.java

/**
 * Generates a XSD when Winery's K/V properties are used. This method is put here instead of
 * WinerysPropertiesDefinitionResource to avoid generating the subresource
 * /*from   www .  j  ava2 s  . co  m*/
 * public because of the usage by TOSCAEXportUtil
 * 
 * @return empty Document, if Winery's Properties Definition is not fully filled (e.g., no
 *         wrapping element defined)
 */
public static Document getWinerysPropertiesDefinitionXSDAsDocument(WinerysPropertiesDefinition wpd) {
    /*
     * This is a quick hack: an XML schema container is created for each element. Smarter
     * solution: create a hash from namespace to XML schema element and re-use that for each new
     * element Drawback of "smarter" solution: not a single XSD file any more
     */
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        ModelUtilities.logger.debug(e.getMessage(), e);
        throw new IllegalStateException("Could not instantiate document builder", e);
    }
    Document doc = docBuilder.newDocument();

    if (!ModelUtilities.allRequiredFieldsNonNull(wpd)) {
        // wpd not fully filled -> valid XSD cannot be provided
        // fallback: add comment and return "empty" document
        Comment comment = doc
                .createComment("Required fields are missing in Winery's key/value properties definition.");
        doc.appendChild(comment);
        return doc;
    }

    // create XSD schema container
    Element schemaElement = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
    doc.appendChild(schemaElement);
    schemaElement.setAttribute("elementFormDefault", "qualified");
    schemaElement.setAttribute("attributeFormDefault", "unqualified");
    schemaElement.setAttribute("targetNamespace", wpd.getNamespace());

    // create XSD element itself
    Element el = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
    schemaElement.appendChild(el);
    el.setAttribute("name", wpd.getElementName());
    Element el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "complexType");
    el.appendChild(el2);
    el = el2;
    el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "sequence");
    el.appendChild(el2);
    el = el2;

    // currently, "xsd" is a hardcoded prefix in the type definition
    el.setAttribute("xmlns:xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);

    for (PropertyDefinitionKV prop : wpd.getPropertyDefinitionKVList()) {
        el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
        el.appendChild(el2);
        el2.setAttribute("name", prop.getKey());
        // prop.getType has the prefix included
        el2.setAttribute("type", prop.getType());
    }

    return doc;
}

From source file:org.eclipse.winery.repository.backend.BackendUtils.java

/**
 * Derives Winery's Properties Definition from an existing properties
 * definition//w w  w  . j a  va  2s . c  om
 * 
 * @param ci the entity type to try to modify the WPDs
 * @param errors the list to add errors to
 */
public static void deriveWPD(TEntityType ci, List<String> errors) {
    BackendUtils.logger.trace("deriveWPD");
    PropertiesDefinition propertiesDefinition = ci.getPropertiesDefinition();
    QName element = propertiesDefinition.getElement();
    if (element == null) {
        BackendUtils.logger.debug("only works for an element definition, not for types");
    } else {
        BackendUtils.logger.debug(
                "Looking for the definition of {" + element.getNamespaceURI() + "}" + element.getLocalPart());
        // fetch the XSD defining the element
        XSDImportsResource importsRes = new XSDImportsResource();
        Map<String, RepositoryFileReference> mapFromLocalNameToXSD = importsRes
                .getMapFromLocalNameToXSD(element.getNamespaceURI(), false);
        RepositoryFileReference ref = mapFromLocalNameToXSD.get(element.getLocalPart());
        if (ref == null) {
            String msg = "XSD not found for " + element.getNamespaceURI() + " / " + element.getLocalPart();
            BackendUtils.logger.debug(msg);
            errors.add(msg);
            return;
        }

        XSModel xsModel = BackendUtils.getXSModel(ref);
        XSElementDeclaration elementDeclaration = xsModel.getElementDeclaration(element.getLocalPart(),
                element.getNamespaceURI());
        if (elementDeclaration == null) {
            String msg = "XSD model claimed to contain declaration for {" + element.getNamespaceURI() + "}"
                    + element.getLocalPart() + ", but it did not.";
            BackendUtils.logger.debug(msg);
            errors.add(msg);
            return;
        }

        // go through the XSD definition and
        XSTypeDefinition typeDefinition = elementDeclaration.getTypeDefinition();
        if (typeDefinition instanceof XSComplexTypeDefinition) {
            XSComplexTypeDefinition cTypeDefinition = (XSComplexTypeDefinition) typeDefinition;
            XSParticle particle = cTypeDefinition.getParticle();
            if (particle == null) {
                BackendUtils.logger.debug(
                        "XSD does not follow the requirements put by winery: Complex type does not contain particles");
            } else {
                XSTerm term = particle.getTerm();
                if (term instanceof XSModelGroup) {
                    XSModelGroup modelGroup = (XSModelGroup) term;
                    if (modelGroup.getCompositor() == XSModelGroup.COMPOSITOR_SEQUENCE) {
                        XSObjectList particles = modelGroup.getParticles();
                        int len = particles.getLength();
                        boolean everyThingIsASimpleType = true;
                        PropertyDefinitionKVList list = new PropertyDefinitionKVList();
                        if (len != 0) {
                            for (int i = 0; i < len; i++) {
                                XSParticle innerParticle = (XSParticle) particles.item(i);
                                XSTerm innerTerm = innerParticle.getTerm();
                                if (innerTerm instanceof XSElementDeclaration) {
                                    XSElementDeclaration innerElementDeclaration = (XSElementDeclaration) innerTerm;
                                    String name = innerElementDeclaration.getName();
                                    XSTypeDefinition innerTypeDefinition = innerElementDeclaration
                                            .getTypeDefinition();
                                    if (innerTypeDefinition instanceof XSSimpleType) {
                                        XSSimpleType xsSimpleType = (XSSimpleType) innerTypeDefinition;
                                        String typeNS = xsSimpleType.getNamespace();
                                        String typeName = xsSimpleType.getName();
                                        if (typeNS.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
                                            PropertyDefinitionKV def = new PropertyDefinitionKV();
                                            def.setKey(name);
                                            // convention at WPD: use "xsd" as prefix for XML Schema Definition
                                            def.setType("xsd:" + typeName);
                                            list.add(def);
                                        } else {
                                            everyThingIsASimpleType = false;
                                            break;
                                        }
                                    } else {
                                        everyThingIsASimpleType = false;
                                        break;
                                    }
                                } else {
                                    everyThingIsASimpleType = false;
                                    break;
                                }
                            }
                        }
                        if (everyThingIsASimpleType) {
                            // everything went allright, we can add a WPD
                            WinerysPropertiesDefinition wpd = new WinerysPropertiesDefinition();
                            wpd.setIsDerivedFromXSD(Boolean.TRUE);
                            wpd.setElementName(element.getLocalPart());
                            wpd.setNamespace(element.getNamespaceURI());
                            wpd.setPropertyDefinitionKVList(list);
                            ModelUtilities.replaceWinerysPropertiesDefinition(ci, wpd);
                            BackendUtils.logger.debug("Successfully generated WPD");
                        } else {
                            BackendUtils.logger.debug(
                                    "XSD does not follow the requirements put by winery: Not all types in the sequence are simple types");
                        }
                    } else {
                        BackendUtils.logger.debug(
                                "XSD does not follow the requirements put by winery: Model group is not a sequence");
                    }
                } else {
                    BackendUtils.logger
                            .debug("XSD does not follow the requirements put by winery: Not a model group");
                }
            }
        } else {
            BackendUtils.logger
                    .debug("XSD does not follow the requirements put by winery: No Complex Type Definition");
        }
    }
}

From source file:org.eclipse.winery.repository.export.TOSCAExportUtil.java

/**
 * Writes the Definitions belonging to the given TOSCA component to the outputstream
 * //from ww  w  . j  a va  2  s. c o m
 * @return a collection of TOSCAcomponentIds referenced by the given component
 * 
 * @throws IOException
 * @throws JAXBException
 * @throws IllegalStateException if tcId does not exist
 */
private Collection<TOSCAComponentId> writeDefinitionsElement(TOSCAComponentId tcId, OutputStream out,
        ExportFileGenerator extendPoint) throws IOException, JAXBException {
    if (!Repository.INSTANCE.exists(tcId)) {
        String error = "Component instance " + tcId.toString() + " does not exist.";
        TOSCAExportUtil.logger.error(error);
        throw new IllegalStateException(error);
    }

    AbstractComponentInstanceResource res = AbstractComponentsResource.getComponentInstaceResource(tcId);
    Definitions entryDefinitions = res.getDefinitions();

    // BEGIN: Definitions modification
    // the "imports" collection contains the imports of Definitions, not of
    // other definitions
    // the other definitions are stored in entryDefinitions.getImport()
    // we modify the internal definitions object directly. It is not written
    // back to the storage. Therefore, we do not need to clone it

    // the imports (pointing to not-definitions (xsd, wsdl, ...)) already
    // have a correct relative URL. (quick hack)
    URI uri = (URI) this.exportConfiguration.get(TOSCAExportUtil.ExportProperties.REPOSITORY_URI.toString());
    if (uri != null) {
        // we are in the plain-XML mode, the URLs of the imports have to be
        // adjusted
        for (TImport i : entryDefinitions.getImport()) {
            String loc = i.getLocation();
            assert (loc.startsWith("../"));
            loc = loc.substring(3);
            loc = uri + loc;
            // now the location is an absolute URL
            i.setLocation(loc);
        }
    }

    // files of imports have to be added to the CSAR, too
    for (TImport i : entryDefinitions.getImport()) {
        String loc = i.getLocation();
        if (Util.isRelativeURI(loc)) {
            // locally stored, add to CSAR
            GenericImportId iid = new GenericImportId(i);
            String fileName = Util.getLastURIPart(loc);
            fileName = Util.URLdecode(fileName);
            RepositoryFileReference ref = new RepositoryFileReference(iid, fileName);
            this.putRefAsReferencedItemInCSAR(ref);
        }
    }

    // adjust imports: add imports of definitions to it
    Collection<TOSCAComponentId> referencedTOSCAComponentIds = this.getReferencedTOSCAComponentIds(tcId);

    Collection<TImport> imports = new ArrayList<>();
    for (TOSCAComponentId id : referencedTOSCAComponentIds) {
        this.addToImports(id, imports);
    }
    entryDefinitions.getImport().addAll(imports);

    if (res.getElement() instanceof TEntityType) {
        // we have an entity type with a possible properties definition
        EntityTypeResource entityTypeRes = (EntityTypeResource) res;
        WinerysPropertiesDefinition wpd = ModelUtilities
                .getWinerysPropertiesDefinition(entityTypeRes.getEntityType());
        if (wpd != null) {
            if (wpd.getIsDerivedFromXSD() == null) {
                // Write WPD only to file if it exists and is NOT derived
                // from an XSD (which may happen during import)

                String wrapperElementNamespace = wpd.getNamespace();
                String wrapperElementLocalName = wpd.getElementName();

                // BEGIN: add import and put into CSAR

                TImport imp = new TImport();
                entryDefinitions.getImport().add(imp);

                // fill known import values
                imp.setImportType(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                imp.setNamespace(wrapperElementNamespace);
                // add "winerysPropertiesDefinition" flag to import tag to
                // support
                Map<QName, String> otherAttributes = imp.getOtherAttributes();
                otherAttributes.put(QNames.QNAME_WINERYS_PROPERTIES_DEFINITION_ATTRIBUTE, "true");

                // Determine location
                String loc = BackendUtils.getImportLocationForWinerysPropertiesDefinitionXSD(
                        (EntityTypeId) tcId, uri, wrapperElementLocalName);
                if (uri == null) {
                    TOSCAExportUtil.logger.trace("CSAR Export mode. Putting XSD into CSAR");
                    // CSAR Export mode
                    // XSD has to be put into the CSAR
                    Document document = ModelUtilities.getWinerysPropertiesDefinitionXSDAsDocument(wpd);

                    // loc in import is URLencoded, loc on filesystem isn't
                    String locInCSAR = Util.URLdecode(loc);
                    // furthermore, the path has to start from the root of
                    // the CSAR; currently, it starts from Definitions/
                    locInCSAR = locInCSAR.substring(3);
                    TOSCAExportUtil.logger.trace("Location in CSAR: {}", locInCSAR);
                    if (!isValueExist(this.referencesToPathInCSARMap, locInCSAR))
                        this.referencesToPathInCSARMap
                                .put(new DummyRepositoryFileReferenceForGeneratedXSD(document), locInCSAR);
                }
                imp.setLocation(loc);

                // END: add import and put into CSAR

                // BEGIN: generate TOSCA conforming PropertiesDefinition

                TEntityType entityType = entityTypeRes.getEntityType();
                PropertiesDefinition propertiesDefinition = new PropertiesDefinition();
                propertiesDefinition.setType(new QName(wrapperElementNamespace, wrapperElementLocalName));
                entityType.setPropertiesDefinition(propertiesDefinition);

                // END: generate TOSCA conforming PropertiesDefinition
            } else {
                // otherwise WPD exists, but is derived from XSD
                // we DO NOT have to remove the winery properties definition
                // from the output to allow "debugging" of the CSAR
            }
        }
    }

    // END: Definitions modification

    if (extendPoint != null) {
        extendPoint.setArchiveFiles(this.yamlExportDefResultList);
        DefinitionResultInfo[] fileResultInfos = extendPoint.makeFile(entryDefinitions, out);
        if (extendPoint instanceof YamlExportFileGenerator) {
            if (Utils.isServiceTemplateDefinition(entryDefinitions)) {
                this.yamlEntryDefinitionsReference = fileResultInfos[0].getFileFullName();
            }
            for (DefinitionResultInfo fileResult : fileResultInfos) {
                yamlExportDefResultList.add(fileResult);
            }
        }
    } else
        this.writeDefinitionsElement(entryDefinitions, out);

    return referencedTOSCAComponentIds;
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Imports the specified types into the repository. The types are converted to an import statement
 * /*from   ww w .  j av  a 2s.c om*/
 * @param errors Container for error messages
 */
private void importTypes(TDefinitions defs, final List<String> errors) {
    Types typesContainer = defs.getTypes();
    if (typesContainer != null) {
        List<Object> types = typesContainer.getAny();
        for (Object type : types) {
            if (type instanceof Element) {
                Element element = (Element) type;

                // generate id part of ImportId out of definitions' id
                // we do not use the name as the name has to be URLencoded again and we have issues with
                // the interplay with
                // org.eclipse.winery.common.ids.definitions.imports.GenericImportId.getId(TImport) then.
                String id = defs.getId();
                // try to make the id unique by hashing the "content" of the definition
                id = id + "-" + Integer.toHexString(element.hashCode());

                // set importId
                TOSCAComponentId importId;
                String ns;
                if (element.getNamespaceURI().equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
                    ns = element.getAttribute("targetNamespace");
                    importId = new XSDImportId(ns, id, false);
                } else {
                    // Quick hack for non-XML-Schema-definitions
                    ns = "unknown";
                    importId = new GenericImportId(ns, id, false, element.getNamespaceURI());
                }

                // Following code is adapted from importOtherImports

                TDefinitions wrapperDefs = BackendUtils.createWrapperDefinitions(importId);
                TImport imp = new TImport();
                String fileName = id + ".xsd";
                imp.setLocation(fileName);
                imp.setImportType(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                imp.setNamespace(ns);
                wrapperDefs.getImport().add(imp);
                CSARImporter.storeDefinitions(importId, wrapperDefs);

                // put the file itself to the repo
                // ref is required to generate fileRef
                RepositoryFileReference ref = BackendUtils.getRefOfDefinitions(importId);
                RepositoryFileReference fileRef = new RepositoryFileReference(ref.getParent(), fileName);
                // convert element to document
                // QUICK HACK. Alternative: Add new method Repository.INSTANCE.getOutputStream and
                // transform DOM node to OuptputStream
                String content = Util.getXMLAsString(element);
                try {
                    Repository.INSTANCE.putContentToFile(fileRef, content, MediaType.APPLICATION_XML_TYPE);
                } catch (IOException e) {
                    CSARImporter.logger
                            .debug("Could not put XML Schema definition to file " + fileRef.toString(), e);
                    errors.add("Could not put XML Schema definition to file " + fileRef.toString());
                }

                // add import to definitions

                // adapt path - similar to importOtherImport
                String newLoc = "../" + Utils.getURLforPathInsideRepo(BackendUtils.getPathInsideRepo(fileRef));
                imp.setLocation(newLoc);
                defs.getImport().add(imp);
            } else {
                // This is a known type. Otherwise JAX-B would render it as Element
                errors.add("There is a Type of class " + type.getClass().toString()
                        + " which is unknown to Winery. The type element is imported as is");
            }
        }
    }
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * SIDE EFFECT: modifies the location of imp to point to the correct relative location (when read
 * from the exported CSAR)/*from   w ww  .  ja v a  2 s . c o  m*/
 * 
 * @param rootPath the absolute path where to resolve files from
 */
private void importOtherImport(Path rootPath, TImport imp, final List<String> errors, String type,
        boolean overwrite) {
    assert (!type.equals(Namespaces.TOSCA_NAMESPACE));
    String loc = imp.getLocation();

    if (!Util.isRelativeURI(loc)) {
        // This is just an information message
        errors.add("Absolute URIs are not resolved by Winery (" + loc + ")");
        return;
    }

    // location URLs are encoded: http://www.w3.org/TR/2001/WD-charmod-20010126/#sec-URIs, RFC
    // http://www.ietf.org/rfc/rfc2396.txt
    loc = Util.URLdecode(loc);
    Path path;
    try {
        path = rootPath.resolve(loc);
    } catch (Exception e) {
        // java.nio.file.InvalidPathException could be thrown which is a RuntimeException
        errors.add(e.getMessage());
        return;
    }
    if (!Files.exists(path)) {
        // fallback for older CSARs, where the location is given from the root
        path = rootPath.getParent().resolve(loc);
        if (!Files.exists(path)) {
            errors.add(String.format("File %1$s does not exist", loc));
            return;
        }
    }
    String namespace = imp.getNamespace();
    String fileName = path.getFileName().toString();
    String id = fileName;
    id = FilenameUtils.removeExtension(id);
    // Convention: id of import is filename without extension

    GenericImportId rid;
    if (type.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
        rid = new XSDImportId(namespace, id, false);
    } else {
        rid = new GenericImportId(namespace, id, false, type);
    }

    boolean importDataExistsInRepo = Repository.INSTANCE.exists(rid);

    if (!importDataExistsInRepo) {
        // We have to
        // a) create a .definitions file
        // b) put the file itself in the repo

        // Create the definitions file
        TDefinitions defs = BackendUtils.createWrapperDefinitions(rid);
        defs.getImport().add(imp);
        // QUICK HACK: We change the imp object's location here and below again
        // This is "OK" as "storeDefinitions" serializes the current state and not the future state of
        // the imp object
        // change the location to point to the file in the folder of the .definitions file
        imp.setLocation(fileName);

        // put the definitions file to the repository
        CSARImporter.storeDefinitions(rid, defs);
    }

    // put the file itself to the repo
    // ref is required to generate fileRef
    RepositoryFileReference ref = BackendUtils.getRefOfDefinitions(rid);
    RepositoryFileReference fileRef = new RepositoryFileReference(ref.getParent(), fileName);

    // location is relative to Definitions/
    // even if the import already exists, we have to adapt the path
    // URIs are encoded
    String newLoc = "../" + Utils.getURLforPathInsideRepo(BackendUtils.getPathInsideRepo(fileRef));
    imp.setLocation(newLoc);

    if (!importDataExistsInRepo || overwrite) {
        // finally write the file to the storage
        try (InputStream is = Files.newInputStream(path);
                BufferedInputStream bis = new BufferedInputStream(is)) {
            MediaType mediaType;
            if (type.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
                mediaType = MediaType.valueOf(MimeTypes.MIMETYPE_XSD);
            } else {
                String mimeType = Utils.getMimeType(bis, path.getFileName().toString());
                mediaType = MediaType.valueOf(mimeType);
            }
            Repository.INSTANCE.putContentToFile(fileRef, bis, mediaType);
        } catch (IllegalArgumentException | IOException e) {
            throw new IllegalStateException(e);
        }

        // we have to update the cache in case of a new XSD to speedup usage of winery
        if (rid instanceof XSDImportId) {
            // We do the initialization asynchronously
            // We do not check whether the XSD has already been checked
            // We cannot just checck whether an XSD already has been handled since the XSD could change
            // over time
            // Synchronization at
            // org.eclipse.winery.repository.resources.imports.xsdimports.XSDImportResource.getAllDefinedLocalNames(short)
            // also isn't feasible as the backend doesn't support locks
            CSARImporter.xsdParsingService.submit(new Runnable() {

                @Override
                public void run() {
                    CSARImporter.logger.debug("Updating XSD import cache data");
                    // We call the queries without storing the result:
                    // We use the SIDEEFFECT that a cache is created
                    Utils.getAllXSDElementDefinitionsForTypeAheadSelection();
                    Utils.getAllXSDTypeDefinitionsForTypeAheadSelection();
                    CSARImporter.logger.debug("Updated XSD import cache data");
                }
            });
        }
    }
}

From source file:org.evosuite.continuous.persistency.StorageManager.java

private static Project getProject(File current, InputStream stream) {
    try {//w ww  .  j  a  v  a2s.  co m
        JAXBContext jaxbContext = JAXBContext.newInstance(Project.class);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(
                new StreamSource(StorageManager.class.getResourceAsStream("/xsd/ctg_project_report.xsd")));
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        return (Project) jaxbUnmarshaller.unmarshal(stream);
    } catch (Exception e) {
        String msg = "Error in reading " + current.getAbsolutePath() + " , " + e;
        logger.error(msg, e);
        throw new RuntimeException(msg);
    }
}