Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;
import java.io.InputStream;

import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    public static Document openUrl(String location) throws Exception {
        URL url = new URL(location);
        //System.out.println(url);

        URLConnection con = url.openConnection();
        InputStream responseStream = con.getInputStream();

        Document result = loadFromStream(responseStream);
        responseStream.close();
        return result;
    }

    public static Document loadFromStream(InputStream inputStream) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(false);

        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                //System.out.println("Ignoring " + publicId + ", " + systemId);
                return new InputSource(new StringReader(""));
            }
        });

        //System.out.println(StringUtil.toString(inputStream));

        Document doc = builder.parse(inputStream);
        return doc;
    }
}