Example usage for org.xml.sax XMLReader parse

List of usage examples for org.xml.sax XMLReader parse

Introduction

In this page you can find the example usage for org.xml.sax XMLReader parse.

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:com.jkoolcloud.tnt4j.streams.inputs.ExcelSXSSFRowStream.java

/**
 * Parses the content of one sheet using the specified styles and shared-strings tables.
 *
 * @param styles// ww w .jav  a  2s . com
 *            the table of styles that may be referenced by cells in the sheet
 * @param strings
 *            the table of strings that may be referenced by cells in the sheet
 * @param sheetHandler
 *            the sheet handler
 * @param sheetInputStream
 *            the input stream to read the sheet-data from
 *
 * @throws IOException
 *             if sheet input stream read fails
 * @throws SAXException
 *             if sheet input stream provided XML can't be parsed
 */
public static void processSXSSFSheet(StylesTable styles, ReadOnlySharedStringsTable strings,
        SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws IOException, SAXException {
    DataFormatter formatter = new DataFormatter();
    InputSource sheetSource = new InputSource(sheetInputStream);
    try {
        XMLReader sheetParser = SAXHelper.newXMLReader();
        ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false);
        sheetParser.setContentHandler(handler);
        sheetParser.parse(sheetSource);
    } catch (ParserConfigurationException exc) {
        throw new RuntimeException(
                StreamsResources.getStringFormatted(MsOfficeStreamConstants.RESOURCE_BUNDLE_NAME,
                        "ExcelSXSSFRowStream.sax.cfg.error", Utils.getExceptionMessages(exc)));
    }
}

From source file:architecture.common.model.factory.ModelTypeFactory.java

private static List<ModelList> parseLegacyXmlFile(List<ModelList> list) throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> enumeration = cl.getResources(IF_PLUGIN_PATH);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*  w ww . jav  a  2  s .  c om*/
    XMLReader xmlreader = factory.newSAXParser().getXMLReader();
    ImplFactoryParsingHandler handler = new ImplFactoryParsingHandler();
    xmlreader.setContentHandler(handler);
    xmlreader.setDTDHandler(handler);
    xmlreader.setEntityResolver(handler);
    xmlreader.setErrorHandler(handler);
    System.out.println("Model Enum:");
    do {
        if (!enumeration.hasMoreElements())
            break;
        URL url = (URL) enumeration.nextElement();
        System.out.println(" - " + url);
        try {
            xmlreader.parse(new InputSource(url.openStream()));
            ModelList factorylist = new ModelList();
            factorylist.rank = handler.rank;
            factorylist.modelTypes.addAll(handler.getModels());
            list.add(factorylist);
        } catch (Exception exception) {
        }
    } while (true);

    return list;
}

From source file:com.mindquarry.desktop.I18N.java

protected static Map<String, String> initTranslationMap(String fileBase, String fileSuffix) {
    try {//www.  j a va 2s  . c  o m
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(false);
        SAXParser parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        TranslationMessageParser translationParser = new TranslationMessageParser();
        reader.setContentHandler(translationParser);
        reader.setErrorHandler(translationParser);
        // TODO: use "xx_YY" if available, use "xx" otherwise:
        String transFile = fileBase + Locale.getDefault().getLanguage() + fileSuffix;
        InputStream is = I18N.class.getResourceAsStream(transFile);
        if (is == null) {
            // no translation available for this language
            log.debug("No translation file available for language: " + Locale.getDefault().getLanguage());
            return new HashMap<String, String>();
        }
        log.debug("Loading translation file " + transFile + " from JAR");
        reader.parse(new InputSource(is));
        return translationParser.getMap();
    } catch (Exception e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:com.mirth.connect.plugins.datatypes.ncpdp.test.NCPDPTest.java

private static long runTest(String testMessage) throws MessageSerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    //      Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    //        properties.put("useStrictParser", "true");
    //        properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource",SchemaUrl);
    stopwatch.start();/*www. ja va 2  s  .  c  o m*/
    NCPDPSerializer serializer = new NCPDPSerializer(null);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.serialize(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:com.mirth.connect.model.converters.tests.NCPDPTest.java

private static long runTest(String testMessage) throws SerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    properties.put("useStrictParser", "true");
    properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource", SchemaUrl);
    stopwatch.start();/*ww w.j  a  v a  2s. com*/
    NCPDPSerializer serializer = new NCPDPSerializer(properties);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.toXML(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:com.binomed.showtime.android.util.CineShowtimeRequestManage.java

public static NearResp searchTheatersOrMovies(Context context, Double latitude, Double longitude,
        String cityName, String movieName, String theaterId, int day, int start, String origin,
        String hourLocalized, String minutesLocalized) throws Exception {

    URLBuilder andShowtimeUriBuilder = new URLBuilder(CineShowTimeEncodingUtil.convertLocaleToEncoding());
    andShowtimeUriBuilder.setProtocol(HttpParamsCst.BINOMED_APP_PROTOCOL);
    andShowtimeUriBuilder.setAdress(getAppEngineUrl(context));
    andShowtimeUriBuilder.completePath(HttpParamsCst.BINOMED_APP_PATH);
    andShowtimeUriBuilder/*from  w ww. j ava2s.co  m*/
            .completePath(((movieName != null) && (movieName.length() > 0)) ? HttpParamsCst.MOVIE_GET_METHODE
                    : HttpParamsCst.NEAR_GET_METHODE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LANG, Locale.getDefault().getLanguage());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OUTPUT, HttpParamsCst.VALUE_XML);
    // andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_ZIP, HttpParamsCst.VALUE_TRUE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_IE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_CURENT_TIME,
            String.valueOf(Calendar.getInstance().getTimeInMillis()));
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_TIME_ZONE, TimeZone.getDefault().getID());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_HOUR_LOCALIZE, hourLocalized);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MIN_LOCALIZE, minutesLocalized);

    if (theaterId != null) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_THEATER_ID //
                , theaterId);
    }
    if (day > 0) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_DAY //
                , String.valueOf(day));
    }
    if (start > 0) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_START //
                , String.valueOf(start));
    }
    String countryCode = Locale.getDefault().getCountry();

    Geocoder geocoder = CineShowtimeFactory.getGeocoder();
    Location originalPlace = null;
    if (geocoder != null) {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "error during decoding", e);
            }
            List<Address> addressList = null;
            try {
                addressList = geocoder.getFromLocationName(cityName, 1);
            } catch (Exception e) {
                Log.e(TAG, "error Searching cityName :" + cityName, e);
            }
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                // if (addressList.get(0).getLocality() != null &&
                // addressList.get(0).getPostalCode() != null) {
                // cityName += " " + addressList.get(0).getPostalCode();
                // }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }

                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());

                countryCode = addressList.get(0).getCountryCode();
            }
            if (cityName != null) {
                andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
            }
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            List<Address> addressList = null;
            try {
                addressList = geocoder.getFromLocation(latitude, longitude, 1);
            } catch (Exception e) {
                Log.e(TAG, "error Searching latitude, longitude :" + latitude + "," + longitude, e);
            }
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getPostalCode() != null)) {
                    cityName += " " + addressList.get(0).getPostalCode();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }
                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());

                countryCode = addressList.get(0).getCountryCode();
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
            if (cityName != null) {
                andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
            }
        }
    } else {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "error during decoding", e);
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
        }
    }
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_COUNTRY_CODE, countryCode);

    if (movieName != null) {
        try {
            movieName = URLDecoder.decode(movieName, CineShowTimeEncodingUtil.getEncoding());
        } catch (Exception e) {
            Log.e(TAG, "error during decoding", e);
        }
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MOVIE_NAME, movieName);
    }

    String uri = andShowtimeUriBuilder.toUri();
    Log.i(TAG, "send request : " + uri); //$NON-NLS-1$
    HttpGet getMethod = CineShowtimeFactory.getHttpGet();
    getMethod.setURI(new URI(uri));
    HttpResponse res = CineShowtimeFactory.getHttpClient().execute(getMethod);

    XMLReader reader = CineShowtimeFactory.getXmlReader();
    ParserNearResultXml parser = CineShowtimeFactory.getParserNearResultXml();
    reader.setContentHandler(parser);
    InputSource inputSource = CineShowtimeFactory.getInputSource();
    // inputSource.setByteStream(new GZIPInputStream(res.getEntity().getContent()));
    inputSource.setByteStream(res.getEntity().getContent());

    reader.parse(inputSource);

    NearResp resultBean = parser.getNearRespBean();
    resultBean.setCityName(cityName);

    return resultBean;
}

From source file:com.zimbra.cs.service.FeedManager.java

@VisibleForTesting
static final String stripXML(String title) {
    if (title == null) {
        return "";
    } else if (title.indexOf('<') == -1 && title.indexOf('&') == -1) {
        return title;
    }//w  ww. j  av  a 2 s  . c o  m

    org.xml.sax.XMLReader parser = new org.cyberneko.html.parsers.SAXParser();
    org.xml.sax.ContentHandler handler = new UnescapedContent();
    parser.setContentHandler(handler);
    try {
        parser.parse(new org.xml.sax.InputSource(new StringReader(title)));
        return handler.toString();
    } catch (Exception e) {
        return title;
    }
}

From source file:TypeInfoWriter.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();/*from www  .ja  v  a2 s  .  c o m*/
        System.exit(1);
    }

    // variables
    XMLReader parser = null;
    Vector schemas = null;
    Vector instances = null;
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;

    // process arguments
    for (int i = 0; i < argv.length; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                    continue;
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                        System.exit(1);
                    }
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: schema documents
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    // use default parser?
    if (parser == null) {
        // create parser
        try {
            parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
        } catch (Exception e) {
            System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
            e.printStackTrace(System.err);
            System.exit(1);
        }
    }

    try {
        // Create writer
        TypeInfoWriter writer = new TypeInfoWriter();
        writer.setOutput(System.out, "UTF8");

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(writer);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        if (schemas != null && schemas.size() > 0) {
            final int length = schemas.size();
            StreamSource[] sources = new StreamSource[length];
            for (int j = 0; j < length; ++j) {
                sources[j] = new StreamSource((String) schemas.elementAt(j));
            }
            schema = factory.newSchema(sources);
        } else {
            schema = factory.newSchema();
        }

        // Setup validator and parser
        ValidatorHandler validator = schema.newValidatorHandler();
        parser.setContentHandler(validator);
        if (validator instanceof DTDHandler) {
            parser.setDTDHandler((DTDHandler) validator);
        }
        parser.setErrorHandler(writer);
        validator.setContentHandler(writer);
        validator.setErrorHandler(writer);
        writer.setTypeInfoProvider(validator.getTypeInfoProvider());

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents and print type information
        if (instances != null && instances.size() > 0) {
            final int length = instances.size();
            for (int j = 0; j < length; ++j) {
                parser.parse((String) instances.elementAt(j));
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:info.magnolia.importexport.DataTransporter.java

/**
 * Imports XML stream into repository./* w w w  .  j  a va 2  s.  c om*/
 * XML is filtered by <code>MagnoliaV2Filter</code>, <code>VersionFilter</code> and <code>ImportXmlRootFilter</code>
 * if <code>keepVersionHistory</code> is set to <code>false</code>
 * @param xmlStream XML stream to import
 * @param repositoryName selected repository
 * @param basepath base path in repository
 * @param name (absolute path of <code>File</code>)
 * @param keepVersionHistory if <code>false</code> version info will be stripped before importing the document
 * @param importMode a valid value for ImportUUIDBehavior
 * @param saveAfterImport
 * @param createBasepathIfNotExist
 * @throws IOException
 * @see ImportUUIDBehavior
 * @see ImportXmlRootFilter
 * @see VersionFilter
 * @see MagnoliaV2Filter
 */
public static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
        String name, boolean keepVersionHistory, int importMode, boolean saveAfterImport,
        boolean createBasepathIfNotExist) throws IOException {

    // TODO hopefully this will be fixed with a more useful message with the Bootstrapper refactoring
    if (xmlStream == null) {
        throw new IOException("Can't import a null stream into repository: " + repositoryName + ", basepath: "
                + basepath + ", name: " + name);
    }

    HierarchyManager hm = MgnlContext.getHierarchyManager(repositoryName);
    if (hm == null) {
        throw new IllegalStateException(
                "Can't import " + name + " since repository " + repositoryName + " does not exist.");
    }
    Workspace ws = hm.getWorkspace();

    if (log.isDebugEnabled()) {
        log.debug("Importing content into repository: [{}] from: [{}] into path: [{}]",
                new Object[] { repositoryName, name, basepath });
    }

    if (!hm.isExist(basepath) && createBasepathIfNotExist) {
        try {
            ContentUtil.createPath(hm, basepath, ItemType.CONTENT);
        } catch (RepositoryException e) {
            log.error("can't create path [{}]", basepath);
        }
    }

    Session session = ws.getSession();

    try {

        // Collects a list with all nodes at the basepath before import so we can see exactly which nodes were imported afterwards
        List<Node> nodesBeforeImport = NodeUtil
                .asList(NodeUtil.asIterable(session.getNode(basepath).getNodes()));

        if (keepVersionHistory) {
            // do not manipulate
            session.importXML(basepath, xmlStream, importMode);
        } else {
            // create readers/filters and chain
            XMLReader initialReader = XMLReaderFactory
                    .createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName());
            try {
                initialReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            } catch (SAXException e) {
                log.error("could not set parser feature");
            }

            XMLFilter magnoliaV2Filter = null;

            // if stream is from regular file, test for belonging XSL file to apply XSL transformation to XML
            if (new File(name).isFile()) {
                InputStream xslStream = getXslStreamForXmlFile(new File(name));
                if (xslStream != null) {
                    Source xslSource = new StreamSource(xslStream);
                    SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory
                            .newInstance();
                    XMLFilter xslFilter = saxTransformerFactory.newXMLFilter(xslSource);
                    magnoliaV2Filter = new MagnoliaV2Filter(xslFilter);
                }
            }

            if (magnoliaV2Filter == null) {
                magnoliaV2Filter = new MagnoliaV2Filter(initialReader);
            }

            XMLFilter versionFilter = new VersionFilter(magnoliaV2Filter);

            // enable this to strip useless "name" properties from dialogs
            // versionFilter = new UselessNameFilter(versionFilter);

            // enable this to strip mix:versionable from pre 3.6 xml files
            versionFilter = new RemoveMixversionableFilter(versionFilter);

            XMLReader finalReader = new ImportXmlRootFilter(versionFilter);

            ContentHandler handler = session.getImportContentHandler(basepath, importMode);
            finalReader.setContentHandler(handler);

            // parse XML, import is done by handler from session
            try {
                finalReader.parse(new InputSource(xmlStream));
            } finally {
                IOUtils.closeQuietly(xmlStream);
            }

            if (((ImportXmlRootFilter) finalReader).rootNodeFound) {
                String path = basepath;
                if (!path.endsWith(SLASH)) {
                    path += SLASH;
                }

                Node dummyRoot = (Node) session.getItem(path + JCR_ROOT);
                for (Iterator iter = dummyRoot.getNodes(); iter.hasNext();) {
                    Node child = (Node) iter.next();
                    // move childs to real root

                    if (session.itemExists(path + child.getName())) {
                        session.getItem(path + child.getName()).remove();
                    }

                    session.move(child.getPath(), path + child.getName());
                }
                // delete the dummy node
                dummyRoot.remove();
            }

            // Post process all nodes that were imported
            NodeIterator nodesAfterImport = session.getNode(basepath).getNodes();
            while (nodesAfterImport.hasNext()) {
                Node nodeAfterImport = nodesAfterImport.nextNode();
                boolean existedBeforeImport = false;
                for (Node nodeBeforeImport : nodesBeforeImport) {
                    if (NodeUtil.isSame(nodeAfterImport, nodeBeforeImport)) {
                        existedBeforeImport = true;
                        break;
                    }
                }
                if (!existedBeforeImport) {
                    postProcessAfterImport(nodeAfterImport);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error importing " + name + ": " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(xmlStream);
    }

    try {
        if (saveAfterImport) {
            session.save();
        }
    } catch (RepositoryException e) {
        log.error(MessageFormat.format(
                "Unable to save changes to the [{0}] repository due to a {1} Exception: {2}.",
                new Object[] { repositoryName, e.getClass().getName(), e.getMessage() }), e);
        throw new IOException(e.getMessage());
    }
}

From source file:com.janoz.tvapilib.support.XmlParsingObject.java

protected void parse(AbstractSaxParser parser, InputStream inputStream) {
    try {//from   w  w  w  .j a  v a2 s. c  o  m
        InputSource input = new InputSource(inputStream);
        input.setPublicId("");
        input.setSystemId("");
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(parser);
        reader.parse(input);
    } catch (SAXException e) {
        LOG.info("Error parsing XML data.", e);
        throw new TvApiException(e.getMessage(), e);
    } catch (IOException e) {
        LOG.info("IO error while parsing XML data.", e);
        throw new TvApiException("IO error while parsing XML data.", e);
    }
}