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.n52.sos.service.it.SosITBase.java

/**
 * Returns a javax.xml.validation Validator that validates xml documents
 * against their internally defined schemas. Constructs the validator if
 * necessary.//  www  .  j  a va  2 s .co  m
 * 
 * @return xmlValidator
 * @throws SAXException
 */
protected Validator getXmlValidator() throws SAXException {
    if (xmlValidator == null) {
        xmlValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema().newValidator();
    }
    return xmlValidator;
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private SpringApplicationService parse(final InputStream xml) throws JAXBException {
    Assert.notNull(xml);/*  w  w  w.  jav  a  2 s.  c  om*/
    final JAXBContext jc = JAXBContext.newInstance(SpringApplicationService.class);
    final Unmarshaller u = jc.createUnmarshaller();
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
    generateSchema(bos);
    try {
        final SpringApplicationService springApplicationService = (SpringApplicationService) u.unmarshal(xml);
        final Schema schema = schemaFactory
                .newSchema(new StreamSource(new ByteArrayInputStream(bos.toByteArray())));
        final Validator validator = schema.newValidator();
        validator.validate(new JAXBSource(jc, springApplicationService));
        return springApplicationService;
    } catch (SAXException | IOException e) {
        throw new IllegalArgumentException(
                "Failed to parse XML. The XML must conform to the following schema:\n" + bos, e);
    }
}

From source file:com.jtstand.swing.Main.java

public Main(String[] args) {
    //BasicConfigurator.configure();

    options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("version", false, "print the version information and exit");
    options.addOption("s", true, "station host name");
    options.addOption("t", true, "title text");
    options.addOption("r", true, "revision number");
    options.addOption("v", true, "version");
    options.addOption("x", true, "schema file location");

    CommandLineParser parser = new PosixParser();
    try {// w  ww .  j a  va  2s.  c  o  m
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jtstand", options);
            System.exit(0);
        } else if (cmd.hasOption("version")) {
            printVersion();
            System.exit(0);
        } else {
            if (cmd.getArgs() != null && cmd.getArgs().length > 0) {
                if (cmd.getArgs().length == 1) {
                    projectLocation = cmd.getArgs()[0];
                } else {
                    log.error("Only one argument is expected; the project location!");
                    log.error("Received arguments:");
                    for (int i = 0; i < cmd.getArgs().length; i++) {
                        log.error(cmd.getArgs()[i]);
                    }
                }
            }
            if (cmd.hasOption("s")) {
                station = cmd.getOptionValue("s");
            }
            if (cmd.hasOption("r")) {
                revision = Integer.parseInt(cmd.getOptionValue("r"));
            }
            if (cmd.hasOption("v")) {
                version = cmd.getOptionValue("v");
            }
            if (cmd.hasOption("t")) {
                title = cmd.getOptionValue("t");
            }
            if (cmd.hasOption("x")) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                String schemaLocation = cmd.getOptionValue("x");
                File schemaFile = new File(schemaLocation);
                if (schemaFile.isFile()) {
                    try {
                        TestProject.setSchema(schemaFactory.newSchema(schemaFile));
                    } catch (SAXException ex) {
                        log.fatal("Exception", ex);
                        javax.swing.JOptionPane.showMessageDialog(null,
                                "Schema file is invalid!\nPress OK to exit.", "Error",
                                javax.swing.JOptionPane.ERROR_MESSAGE);
                        System.exit(-1);
                    }
                } else {
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Schema file cannot be opened!\nPress OK to continue.", "Warning",
                            javax.swing.JOptionPane.WARNING_MESSAGE);
                }
            }
            startProject();
        }
    } catch (ParseException e) {
        log.fatal("Parsing failed" + e);
        System.exit(-1);
    }
}

From source file:com.panet.imeta.trans.steps.xsdvalidator.XsdValidator.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XsdValidatorMeta) smi;//from   ww w  . ja va2s . c om
    data = (XsdValidatorData) sdi;

    Object[] row = getRow();

    if (row == null) // no more input to be expected...
    {
        setOutputDone();
        return false;
    }

    if (first) {
        first = false;
        data.outputRowMeta = getInputRowMeta().clone();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this);

        // Check if XML stream is given
        if (meta.getXMLStream() != null) {
            // Try to get XML Field index
            data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream());
            // Let's check the Field
            if (data.xmlindex < 0) {
                // The field is unreachable !
                logError(Messages.getString("XsdValidator.Log.ErrorFindingField") + "[" + meta.getXMLStream() //$NON-NLS-1$//$NON-NLS-2$
                        + "]");
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.CouldnotFindField", meta.getXMLStream())); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Let's check that Result Field is given
            if (meta.getResultfieldname() == null) {
                //   Result field is missing !
                logError(Messages.getString("XsdValidator.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Is XSD file is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
                if (meta.getXSDFilename() == null) {
                    logError(Messages.getString("XsdValidator.Log.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    // Is XSD file exists ?
                    FileObject xsdfile = null;
                    try {
                        xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename()));
                        if (!xsdfile.exists()) {
                            logError(Messages.getString("XsdValidator.Log.Error.XSDFileNotExists"));
                            throw new KettleStepException(
                                    Messages.getString("XsdValidator.Exception.XSDFileNotExists"));
                        }

                    } catch (Exception e) {
                        logError(Messages.getString("XsdValidator.Log.Error.GettingXSDFile"));
                        throw new KettleStepException(
                                Messages.getString("XsdValidator.Exception.GettingXSDFile"));
                    } finally {
                        try {
                            if (xsdfile != null)
                                xsdfile.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }

            // Is XSD field is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
                if (meta.getXSDDefinedField() == null) {
                    logError(Messages.getString("XsdValidator.Log.Error.XSDFieldMissing"));
                    throw new KettleStepException(Messages.getString("XsdValidator.Exception.XSDFieldMissing"));
                } else {
                    // Let's check if the XSD field exist
                    // Try to get XML Field index
                    data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField());

                    if (data.xsdindex < 0) {
                        // The field is unreachable !
                        logError(Messages.getString("XsdValidator.Log.ErrorFindingXSDField", //$NON-NLS-1$
                                meta.getXSDDefinedField())); //$NON-NLS-2$
                        throw new KettleStepException(Messages.getString(
                                "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
            }

        } else {
            // XML stream field is missing !
            logError(Messages.getString("XsdValidator.Log.Error.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            throw new KettleStepException(Messages.getString("XsdValidator.Exception.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    boolean sendToErrorRow = false;
    String errorMessage = null;

    try {

        // Get the XML field value
        String XMLFieldvalue = getInputRowMeta().getString(row, data.xmlindex);

        boolean isvalid = false;

        // XSD filename
        String xsdfilename = null;

        if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
            xsdfilename = environmentSubstitute(meta.getXSDFilename());
        } else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
            // Get the XSD field value
            xsdfilename = getInputRowMeta().getString(row, data.xsdindex);
        }

        // Get XSD filename
        FileObject xsdfile = null;
        String validationmsg = null;
        try {

            SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            xsdfile = KettleVFS.getFileObject(xsdfilename);
            File XSDFile = new File(KettleVFS.getFilename(xsdfile));

            //   Get XML stream      
            Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue));

            if (meta.getXMLSourceFile()) {

                // We deal with XML file
                // Get XML File
                File xmlfileValidator = new File(XMLFieldvalue);
                if (!xmlfileValidator.exists()) {
                    logError(Messages.getString("XsdValidator.Log.Error.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                }
                sourceXML = new StreamSource(xmlfileValidator);
            }

            // Create XSD schema
            Schema SchematXSD = factoryXSDValidator.newSchema(XSDFile);

            if (meta.getXSDSource().equals(meta.NO_NEED)) {
                // ---Some documents specify the schema they expect to be validated against, 
                // ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes
                //---Schema SchematXSD = factoryXSDValidator.newSchema();
                SchematXSD = factoryXSDValidator.newSchema();
            }

            // Create XSDValidator
            Validator XSDValidator = SchematXSD.newValidator();
            // Validate XML / XSD      
            XSDValidator.validate(sourceXML);

            isvalid = true;

        } catch (SAXException ex) {
            validationmsg = ex.getMessage();
            logError("SAX Exception : " + ex);
        } catch (IOException ex) {
            validationmsg = ex.getMessage();
            logError("SAX Exception : " + ex);
        } finally {
            try {
                if (xsdfile != null)
                    xsdfile.close();

            } catch (IOException e) {
            }
        }

        Object[] outputRowData = null;
        Object[] outputRowData2 = null;

        if (meta.getOutputStringField()) {
            // Output type=String
            if (isvalid)
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlValid()));
            else
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlInvalid()));
        } else {
            outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), isvalid);
        }

        if (meta.useAddValidationMessage())
            outputRowData2 = RowDataUtil.addValueData(outputRowData, getInputRowMeta().size() + 1,
                    validationmsg);
        else
            outputRowData2 = outputRowData;

        if (log.isRowLevel())
            logRowlevel(
                    Messages.getString("XsdValidator.Log.ReadRow") + " " + getInputRowMeta().getString(row));

        //   add new values to the row.
        putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s);
    } catch (KettleException e) {
        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        }

        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001");
        } else {
            logError(Messages.getString("XsdValidator.ErrorProcesing" + " : " + e.getMessage()));
            throw new KettleStepException(Messages.getString("XsdValidator.ErrorProcesing"), e);
        }
    }

    return true;

}

From source file:com.amalto.core.metadata.ClassRepository.java

private TypeMetadata loadClass(Class clazz) {
    String typeName = getTypeName(clazz);
    if (getType(typeName) != null) { // If already defined return it.
        return getType(typeName);
    } else if (getNonInstantiableType(StringUtils.EMPTY, typeName) != null) {
        return getNonInstantiableType(StringUtils.EMPTY, typeName);
    }//from  www.ja  v a2  s  . c  o m
    entityToJavaClass.put(typeName, clazz);
    if (Map.class.isAssignableFrom(clazz)) {
        return MAP_TYPE;
    }
    if (ArrayListHolder.class.equals(clazz)) {
        typeName = typeName + listCounter++;
    }
    boolean isEntity = typeStack.isEmpty();
    ComplexTypeMetadata classType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, typeName, isEntity);
    addTypeMetadata(classType);
    typeStack.push(classType);
    String keyFieldName = ""; //$NON-NLS-1$
    if (isEntity && ObjectPOJO.class.isAssignableFrom(clazz)) {
        SimpleTypeFieldMetadata keyField = new SimpleTypeFieldMetadata(typeStack.peek(), true, false, true,
                "unique-id", //$NON-NLS-1$
                STRING, Collections.<String>emptyList(), Collections.<String>emptyList(),
                Collections.<String>emptyList(), StringUtils.EMPTY);
        keyField.setData(LINK, "PK/unique-id"); //$NON-NLS-1$
        classType.addField(keyField);
    } else if (isEntity) {
        keyFieldName = "unique-id"; //$NON-NLS-1$
    }
    // Class is abstract / interface: load sub classes
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        Iterable<Class> subClasses = getSubclasses(clazz);
        ComplexTypeMetadata superType = typeStack.peek();
        if (superType.isInstantiable()) {
            typeStack.clear();
        }
        for (Class subClass : subClasses) {
            TypeMetadata typeMetadata = loadClass(subClass);
            typeMetadata.setInstantiable(superType.isInstantiable());
            typeMetadata.addSuperType(superType);
        }
        if (superType.isInstantiable()) {
            typeStack.push(superType);
        }
    }
    // Analyze methods
    Method[] classMethods = getMethods(clazz);
    for (Method declaredMethod : classMethods) {
        if (!Modifier.isStatic(declaredMethod.getModifiers())) {
            if (isBeanMethod(declaredMethod) && isClassMethod(clazz, declaredMethod)) {
                String fieldName = getName(declaredMethod);
                if (typeStack.peek().hasField(fieldName)) {
                    continue; // TODO Avoid override of fields (like PK)
                }
                Class<?> returnType = declaredMethod.getReturnType();
                FieldMetadata newField;
                boolean isMany = false;
                boolean isKey = keyFieldName.equals(fieldName);
                if (Iterable.class.isAssignableFrom(returnType)) {
                    returnType = listItemType != null ? listItemType
                            : getListItemClass(declaredMethod, returnType);
                    listItemType = null;
                    isMany = true;
                } else if (ArrayListHolder.class.isAssignableFrom(returnType)) {
                    listItemType = getListItemClass(declaredMethod, returnType);
                    isMany = false;
                } else if (Map.class.isAssignableFrom(returnType)) {
                    isMany = true;
                } else if (returnType.isArray()) {
                    isMany = true;
                    returnType = ((Class) returnType.getComponentType());
                } else if (returnType.getName().startsWith("org.w3c.")) { //$NON-NLS-1$
                    // TODO Serialized XML to string column
                    continue;
                } else if (Class.class.equals(returnType)) {
                    continue;
                } else if (returnType.getPackage() != null
                        && returnType.getPackage().getName().startsWith("java.io")) { //$NON-NLS-1$
                    continue;
                }
                if (returnType.isPrimitive() || returnType.getName().startsWith(JAVA_LANG_PREFIX)) {
                    String fieldTypeName = returnType.getName().toLowerCase();
                    if (fieldTypeName.startsWith(JAVA_LANG_PREFIX)) {
                        fieldTypeName = StringUtils.substringAfter(fieldTypeName, JAVA_LANG_PREFIX);
                    }
                    TypeMetadata fieldType;
                    if (Types.BYTE.equals(fieldTypeName) && isMany) {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                Types.BASE64_BINARY);
                    } else {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldTypeName);
                    }
                    newField = new SimpleTypeFieldMetadata(typeStack.peek(), isKey, isMany, isKey, fieldName,
                            fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(),
                            Collections.<String>emptyList(), StringUtils.EMPTY);
                    LongString annotation = declaredMethod.getAnnotation(LongString.class);
                    if (Types.STRING.equals(fieldTypeName) && annotation != null) {
                        fieldType.setData(MetadataRepository.DATA_MAX_LENGTH,
                                String.valueOf(Integer.MAX_VALUE));
                        if (annotation.preferLongVarchar()) {
                            fieldType.setData(LongString.PREFER_LONGVARCHAR, Boolean.TRUE);
                        }
                    }
                } else {
                    ComplexTypeMetadata fieldType;
                    if (Map.class.isAssignableFrom(returnType)) {
                        fieldType = MAP_TYPE;
                    } else {
                        fieldType = (ComplexTypeMetadata) loadClass(returnType);
                    }
                    if (!isEntity || !fieldType.isInstantiable()) {
                        newField = new ContainedTypeFieldMetadata(typeStack.peek(), isMany, false, fieldName,
                                new SoftTypeRef(this, StringUtils.EMPTY, fieldType.getName(), false),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY);
                    } else {
                        newField = new ReferenceFieldMetadata(typeStack.peek(), false, isMany, false, fieldName,
                                fieldType, fieldType.getField("unique-id"), //$NON-NLS-1$
                                Collections.<FieldMetadata>emptyList(), StringUtils.EMPTY, true, false, STRING,
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY, StringUtils.EMPTY);
                    }
                }
                typeStack.peek().addField(newField);
            }
        }
    }

    typeStack.peek().addField(new SimpleTypeFieldMetadata(typeStack.peek(), false, false, false, "digest", //$NON-NLS-1$
            new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING),
            Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(),
            StringUtils.EMPTY));

    return typeStack.pop();
}

From source file:eu.planets_project.tb.gui.backing.exp.utils.ExpTypeWeeUtils.java

private void checkValidXMLConfig(InputStream xmlWFConfig) throws Exception {
    InputStream bis = getClass().getClassLoader().getResourceAsStream("planets_wdt.xsd");
    try {/*from   w  w  w .  j  a  va2  s.  c  o m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(bis));
        Validator validator = schema.newValidator();
        // Validate file against schema
        XMLOutputter outputter = new XMLOutputter();
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(xmlWFConfig);
        validator.validate(new StreamSource(new StringReader(outputter.outputString(doc.getRootElement()))));
    } catch (Exception e) {
        String err = "The provided xmlWFConfig is not valid against the currently used planets_wdt_xsd schema";
        log.debug(err, e);
        throw new Exception(err, e);
    } finally {
        bis.close();
    }
}

From source file:com.amalto.core.storage.hibernate.FlatTypeMappingCreator.java

@Override
public TypeMapping visit(ComplexTypeMetadata complexType) {
    typeMapping = new FlatTypeMapping(complexType, FlatTypeMappingCreator.this.mappings);
    Collection<FieldMetadata> fields = complexType.getFields();
    for (FieldMetadata field : fields) {
        field.accept(this);
    }/*from   w  w  w. j av  a2s . co m*/
    Collection<FieldMetadata> keyFields = complexType.getKeyFields();
    ComplexTypeMetadata database = typeMapping.getDatabase();
    database.setData(TypeMapping.USAGE_NUMBER, complexType.getUsages().size());
    Collection<TypeMetadata> superTypes = complexType.getSuperTypes();
    for (TypeMetadata superType : superTypes) {
        database.addSuperType(
                new SoftTypeRef(internalRepository, superType.getNamespace(), superType.getName(), true));
    }
    forceKey = true;
    for (FieldMetadata keyField : keyFields) {
        database.registerKey(typeMapping.getDatabase(keyField));
    }
    forceKey = false;
    if (typeMapping.getUser().getKeyFields().isEmpty() && typeMapping.getUser().getSuperTypes().isEmpty()) { // Assumes super type defines key field.
        SoftTypeRef type = new SoftTypeRef(internalRepository, XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING,
                false);
        SimpleTypeFieldMetadata fieldMetadata = new SimpleTypeFieldMetadata(database, true, false, true,
                ScatteredMappingCreator.GENERATED_ID, type, Collections.<String>emptyList(),
                Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY);
        database.addField(fieldMetadata);
    }
    return typeMapping;
}

From source file:com.amalto.core.storage.hibernate.FullTextQueryHandler.java

private StorageResults createResults(final List list) {
    CloseableIterator<DataRecord> iterator;
    if (selectedFields.isEmpty()) {
        iterator = new ListIterator(mappings, storageClassLoader, list.iterator(), callbacks);
    } else {/*from w  w w. j  a v a 2 s. c  o  m*/
        iterator = new ListIterator(mappings, storageClassLoader, list.iterator(), callbacks) {
            @Override
            public DataRecord next() {
                final DataRecord next = super.next();
                final ComplexTypeMetadata explicitProjectionType = new ComplexTypeMetadataImpl(
                        StringUtils.EMPTY, Storage.PROJECTION_TYPE, false);
                final DataRecord nextRecord = new DataRecord(explicitProjectionType,
                        UnsupportedDataRecordMetadata.INSTANCE);
                VisitorAdapter<Void> visitor = new VisitorAdapter<Void>() {
                    private String aliasName;

                    @Override
                    public Void visit(Field field) {
                        FieldMetadata fieldMetadata = field.getFieldMetadata();
                        TypeMapping mapping = mappings
                                .getMappingFromDatabase(fieldMetadata.getContainingType());
                        if (mapping != null && mapping.getUser(fieldMetadata) != null) {
                            fieldMetadata = mapping.getUser(fieldMetadata);
                        }
                        Object value;
                        if (fieldMetadata instanceof ReferenceFieldMetadata) {
                            value = getReferencedId(next, (ReferenceFieldMetadata) fieldMetadata);
                        } else {
                            value = next.get(fieldMetadata);
                        }
                        if (aliasName != null) {
                            SimpleTypeMetadata fieldType = new SimpleTypeMetadata(
                                    XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldMetadata.getType().getName());
                            fieldMetadata = new SimpleTypeFieldMetadata(explicitProjectionType, false, false,
                                    false, aliasName, fieldType, Collections.<String>emptyList(),
                                    Collections.<String>emptyList(), Collections.<String>emptyList(),
                                    StringUtils.EMPTY);
                            explicitProjectionType.addField(fieldMetadata);
                        } else {
                            explicitProjectionType.addField(fieldMetadata);
                        }
                        nextRecord.set(fieldMetadata, value);
                        return null;
                    }

                    @Override
                    public Void visit(StringConstant constant) {
                        if (aliasName != null) {
                            SimpleTypeMetadata fieldType = new SimpleTypeMetadata(
                                    XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING);
                            FieldMetadata fieldMetadata = new SimpleTypeFieldMetadata(explicitProjectionType,
                                    false, false, false, aliasName, fieldType, Collections.<String>emptyList(),
                                    Collections.<String>emptyList(), Collections.<String>emptyList(),
                                    StringUtils.EMPTY);
                            explicitProjectionType.addField(fieldMetadata);
                            nextRecord.set(fieldMetadata, constant.getValue());
                        } else {
                            throw new IllegalStateException("Expected an alias for a constant expression.");
                        }
                        return null;
                    }

                    @Override
                    public Void visit(Count count) {
                        if (aliasName != null) {
                            SimpleTypeMetadata fieldType = new SimpleTypeMetadata(
                                    XMLConstants.W3C_XML_SCHEMA_NS_URI, count.getTypeName());
                            FieldMetadata fieldMetadata = new SimpleTypeFieldMetadata(explicitProjectionType,
                                    false, false, false, aliasName, fieldType, Collections.<String>emptyList(),
                                    Collections.<String>emptyList(), Collections.<String>emptyList(),
                                    StringUtils.EMPTY);
                            explicitProjectionType.addField(fieldMetadata);
                            nextRecord.set(fieldMetadata, list.size());
                        }
                        return null;
                    }

                    @Override
                    public Void visit(Alias alias) {
                        aliasName = alias.getAliasName();
                        {
                            alias.getTypedExpression().accept(this);
                        }
                        aliasName = null;
                        return null;
                    }

                    private Void handleMetadataField(MetadataField field) {
                        SimpleTypeMetadata fieldType = new SimpleTypeMetadata(
                                XMLConstants.W3C_XML_SCHEMA_NS_URI, field.getTypeName());
                        String fieldName = aliasName == null ? field.getFieldName() : aliasName;
                        SimpleTypeFieldMetadata aliasField = new SimpleTypeFieldMetadata(explicitProjectionType,
                                false, false, false, fieldName, fieldType, Collections.<String>emptyList(),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                StringUtils.EMPTY);
                        explicitProjectionType.addField(aliasField);
                        nextRecord.set(aliasField, field.getReader().readValue(next));
                        return null;
                    }

                    @Override
                    public Void visit(Timestamp timestamp) {
                        return handleMetadataField(timestamp);
                    }

                    @Override
                    public Void visit(TaskId taskId) {
                        return handleMetadataField(taskId);
                    }

                    @Override
                    public Void visit(StagingStatus stagingStatus) {
                        return handleMetadataField(stagingStatus);
                    }

                    @Override
                    public Void visit(StagingError stagingError) {
                        return handleMetadataField(stagingError);
                    }

                    @Override
                    public Void visit(StagingSource stagingSource) {
                        return handleMetadataField(stagingSource);
                    }

                    @Override
                    public Void visit(StagingBlockKey stagingBlockKey) {
                        return handleMetadataField(stagingBlockKey);
                    }

                    @Override
                    public Void visit(Type type) {
                        FieldMetadata fieldMetadata = type.getField().getFieldMetadata();
                        SimpleTypeMetadata fieldType = new SimpleTypeMetadata(
                                XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING);
                        SimpleTypeFieldMetadata aliasField = new SimpleTypeFieldMetadata(explicitProjectionType,
                                false, false, false, aliasName, fieldType, Collections.<String>emptyList(),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                StringUtils.EMPTY);
                        explicitProjectionType.addField(aliasField);
                        DataRecord dataRecord = (DataRecord) next.get(fieldMetadata.getName());
                        if (dataRecord != null) {
                            nextRecord.set(aliasField, dataRecord.getType().getName());
                        } else {
                            nextRecord.set(aliasField, StringUtils.EMPTY);
                        }
                        return null;
                    }
                };
                for (TypedExpression selectedField : selectedFields) {
                    selectedField.accept(visitor);
                }
                return nextRecord;
            }
        };
    }
    return new FullTextStorageResults(pageSize, list.size(), iterator);
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

private static Object validate(final Unmarshaller unmarshaller,
        final ValidationEventHandler validationEventHandler, final Reader reader,
        final boolean includeMetaDataSchema) throws JAXBException, SAXException, IOException {

    Object jaxbObject = null;/*from  ww  w .  j  ava 2s.com*/
    try {
        // Set the schema for the unmarshaller
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory
                .newSchema(getSchemaSources(includeMetaDataSchema).toArray(new Source[] {}));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(validationEventHandler);

        // Unmarshal and validate
        jaxbObject = unmarshaller.unmarshal(reader);
    } catch (UnmarshalException ue) {
        // Swallow the exception. The ValidationEventHandler attached to the unmarshaller will
        // contain the validation events
        logger.info(ue);
    }

    return jaxbObject;
}