Example usage for org.jdom2.input SAXBuilder build

List of usage examples for org.jdom2.input SAXBuilder build

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder build.

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

From source file:multiprocDM.wow.java

public static void main(String[] args) {
    SAXBuilder sxb = new SAXBuilder();
    try {/*from  w  w w  . j av a2 s  .  co  m*/
        Document document = sxb.build(new File("mpts30.xml"));
        Element racine = document.getRootElement();
        for (Element taskset : racine.getChildren("taskset")) {
            for (Element task : taskset.getChildren("Task")) {
                if (task.getAttribute("Compute").getLongValue() > task.getAttribute("Deadline").getLongValue())
                    System.exit(0);
            }
        }
        System.out.println("Ok");
        //System.out.println(racine.getChildren("taskset").get(250).getChildren("Task").get(9).getAttribute("Compute").getLongValue());
    } catch (Exception e) {
    }
}

From source file:mx.com.pixup.portal.demo.ValidateXSDXMLCancion.java

public static void main(String[] args) throws IOException, JDOMException {

    try {// w w w.  jav a  2 s .  c om
        //Create the XMLReaderJDOMFacotory directly using the schema file instead of 'Schema'
        String schemaFile = "";
        String file = "";

        XMLReaderJDOMFactory factory2 = new XMLReaderXSDFactory(schemaFile);
        SAXBuilder sb2 = new SAXBuilder(factory2);
        Document doc2 = sb2.build(new File(file));
        System.out.println("ok");
        System.out.println(doc2.getRootElement().getName());
    } catch (org.jdom2.input.JDOMParseException e) {
        e.getLineNumber();
        System.out.println("error");
    }
}

From source file:myjdom.PrettyPrinter.java

public static void main(String[] args) {
    try {/*from  w  w  w.  j  a  v a2 s . co  m*/
        // Build the document with SAXBuilder of JDOM, 
        SAXBuilder builder = new SAXBuilder();
        //builder.setFeature("http://xml.org/sax/features/external-general-entities", false);//NOT WORKING
        //builder.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);//NOT WORKING
        //builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);// WORKING
        // Create the document
        Document doc = builder.build(PrettyPrinter.class.getResourceAsStream(Utils.INTERNAL_XML_LOCATION));//(new File(filename));
        // Output the document, use standard formatter
        XMLOutputter fmt = new XMLOutputter();
        fmt.output(doc, System.out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:mymeteocal.boundary.ImportBean.java

/**
 * Imports the calendar from the uploaded XML file.
 *//*from   w  w w  .ja  va2  s . co m*/
private void importCalendar(UploadedFile file) {

    SAXBuilder builder = new SAXBuilder();

    try {

        InputStream is = file.getInputstream();

        Document doc = builder.build(is);

        updateCalendarFromXML(doc);

    } catch (IOException | JDOMException ex) {

        throw new IllegalArgumentException("Unable to import the calendar.");
    } catch (IllegalArgumentException ex) {

        throw new IllegalArgumentException(ex.getMessage());
    }
}

From source file:negocio.Metodos.java

public ArrayList<Franquicia> leerFranquicias(String nombreFichero) {
    SAXBuilder saxBuilder = new SAXBuilder();
    ArrayList<Franquicia> franquicias = new ArrayList<>();
    /*se crea el file*/
    File file = new File(nombreFichero);
    try {//from w  w w. jav a2 s. co  m
        //se convierte a document
        Document documento = saxBuilder.build(file);
        Element rootNode = documento.getRootElement();
        List<Element> elementosFranquicia = rootNode.getChildren("franquicia");
        Franquicia f;
        for (Element franquicia : elementosFranquicia) {
            f = new Franquicia(Integer.parseInt(franquicia.getAttributeValue("id")),
                    franquicia.getAttributeValue("formato"));
            franquicias.add(f);
        }
    } catch (JDOMException | IOException e) {
        System.out.println("Error al leer franquicias");
    }
    return franquicias;
}

From source file:neon.ui.graphics.svg.SVGLoader.java

License:Open Source License

public static JVShape loadShape(String shape) {
    StringReader stringReader = new StringReader(shape);
    SAXBuilder builder = new SAXBuilder();
    // doc al initialiseren, in geval builder.build faalt
    Document doc = new Document();
    try {/*  www.j  av a  2 s .c om*/
        doc = builder.build(stringReader);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Element root = doc.getRootElement();
    root.detach();
    return loadShape(root);
}

From source file:net.bluehornreader.service.RssParser.java

License:Open Source License

public Results parseRdf(String addr, String feedId, long earliestToInclude) throws Exception {
    //ttt1 review earliestToInclude; quite likely its usage adds duplicates or misses entries; probably don't add 1 to avoid losses and have
    //      FeedCrawlerService check before saving if an article already exists
    // ttt2 see if how to deal with new articles that have an older publish time; currently they are discarded

    LOG.info(String.format("Parsing feed %s from %s (%s)", feedId, earliestToInclude,
            fmt.format(new Date(earliestToInclude))));
    Results results = new Results();

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(addr);
    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        InputStream in = entity.getContent();
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(in);

        Element rootNode = document.getRootElement();
        List<Element> channels = rootNode.getChildren("channel");
        for (Element channel : channels) {
            if (results.feedName.isEmpty()) {
                Element feedTitle = channel.getChild("title");
                if (feedTitle != null) {
                    results.feedName = feedTitle.getText();
                    LOG.info(String.format("Found name %s for feed %s", results.feedName, feedId));
                    //results.feedName = "";
                }/*w  w w  .j  ava2s.  c  om*/
            }
            List<Element> items = channel.getChildren("item");
            for (Element item : items) {
                Element title = item.getChild("title");
                Element link = item.getChild("link");
                Element pubDate = item.getChild("pubDate");

                if (pubDate == null) {
                    // ttt2 apparently pubDate is optional; not sure what to do in such a case
                    LOG.error("Missing pubDate when parsing feed " + feedId);
                } else {
                    long publishTime = fmt.parse(pubDate.getText()).getTime();
                    if (publishTime >= earliestToInclude) {
                        Article article = new Article(feedId, 0, cleanTitle(title.getText()), "",
                                link.getText(), "", publishTime);
                        results.articles.add(article);
                    }
                }
            }
        }
        in.close();
    }

    Collections.sort(results.articles, new Comparator<Article>() {
        @Override
        public int compare(Article o1, Article o2) {
            long a = o1.publishTime - o2.publishTime;
            return a > 0 ? 1 : a < 0 ? -1 : 0;
        }
    });
    LOG.info(String.format("Done parsing feed %s from %s (%s)", feedId, earliestToInclude,
            fmt.format(new Date(earliestToInclude))));
    return results;
}

From source file:net.exclaimindustries.paste.braket.server.TeamDownloader.java

License:Open Source License

/**
 * Download and parse the team information from the ESPN feed, one team at a
 * time.//w  w w  . ja  v  a2 s.c  om
 * 
 * @param tournament
 *            The tournament to which the teams should be referenced.
 * @param teamIds
 *            The Ids of the teams to download (valid numbers are 1 to about
 *            545 or so)
 * @return A list of parsed teams from the ESPN feed, with the endTeamId
 *         excluded.
 * @throws IOException
 * @throws JDOMException
 */
public static Collection<Team> downloadTeams(Iterable<Long> teamIds) throws IOException {
    LinkedList<Team> teamList = new LinkedList<Team>();

    for (Long iTeam : teamIds) {
        URI uri = URI.create(feedString + iTeam.toString());
        SAXBuilder feedParser = new SAXBuilder();
        Document feedDocument;
        try {
            feedDocument = feedParser.build(uri.toURL());
        } catch (JDOMException e) {
            throw new IOException(e);
        }

        Team team = parseTeam(feedDocument);

        if (team == null) {
            // Couldn't find any info about the team, so skip it.
            continue;
        }

        // Make sure that the given ID matches the ID in the team (else this
        // is not a real team)
        if (!team.getId().equals(iTeam)) {
            continue;
        }

        teamList.add(team);
    }

    return teamList;
}

From source file:net.FriendsUnited.Services.FileClient.java

License:Open Source License

private void parseResponse(FriendPacket response, PrintWriter out) {
    log.debug("{}", response);
    ByteConverter responseBc = new ByteConverter(response.getPayload());
    byte type = responseBc.getByte();
    log.debug("Response Type : {}", type);
    switch (type) {
    case FileServer.FAILURE:
        String errorMsg = responseBc.getString();
        if (true == "OK".equals(errorMsg)) {
            out.println("OK");
        } else {/*from   w  w  w.  ja  v  a  2s.c  o m*/
            out.println("ERROR in Response Packet:" + errorMsg);
        }
        break;

    case FileServer.DIRECTORY_LISTING:
        out.println("Listing  of " + RemoteServer + " : " + RemotePath);
        String xmlData = responseBc.getString();
        log.info("Response String : {}", xmlData);
        final SAXBuilder builder = new SAXBuilder();
        Document doc;
        try {
            doc = builder.build(new StringReader(xmlData));
            Element root = null;
            root = doc.getRootElement();
            List<Element> le = root.getChildren();
            for (int i = 0; i < le.size(); i++) {
                Element curentElement = le.get(i);
                String date = curentElement.getChildText("lastModified");
                long ms = Long.parseLong(date);
                Date d = new Date(ms);
                out.printf("%29s", d);
                out.print("|");
                String size = curentElement.getChildText("Size");
                if (null == size) {
                    size = "";
                }
                out.printf("%12s", size);
                out.print("|");
                if (true == "File".equals(curentElement.getName())) {
                    out.print("F");
                } else if (true == "Directory".equals(curentElement.getName())) {
                    out.print("D");
                } else {
                    out.print("X");
                }
                out.print("|");
                out.println(curentElement.getText()); // File Name
            }
        } catch (JDOMException e) {
            log.error(Tool.fromExceptionToString(e));
        } catch (IOException e) {
            log.error(Tool.fromExceptionToString(e));
        }
        break;

    default:
        out.println("ERROR: Receive Response of invalid Type ! "
                + Tool.fromByteBufferToHexString(response.getPayload()));
        break;
    }
}

From source file:net.osgiliath.helpers.camel.ThrownExceptionMessageToInBodyProcessor.java

License:Apache License

@Override
public void process(Exchange exchange) throws Exception {
    final HttpOperationFailedException exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT,
            HttpOperationFailedException.class);
    if (null != exception
            && null != exception.getResponseHeaders().get(ExceptionMappingConstants.EXCEPTION_BODY_HEADER)) {
        final String body = exception.getResponseHeaders().get(ExceptionMappingConstants.EXCEPTION_BODY_HEADER);
        LOG.info("Catched error in route: " + body);
        final SAXBuilder sxb = new SAXBuilder();
        final Document doc = sxb.build(new StringReader(body));
        exchange.getIn()/* w w w .j  a va2  s.  com*/
                .setBody(doc.getRootElement().getChild(ExceptionMappingConstants.EXCEPTION_MESSAGE).getText());
    }
}