Example usage for javax.xml.stream XMLStreamReader close

List of usage examples for javax.xml.stream XMLStreamReader close

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader close.

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Frees any resources associated with this Reader.

Usage

From source file:org.openanzo.services.serialization.XMLNamedGraphUpdatesReader.java

/**
 * Parse the data within the reader, passing the results to the IRepositoryHandler
 * //www. j  a v  a2 s  .  c  o  m
 * @param reader
 *            reader containing the data
 * @param handler
 *            Handler which will handle the elements within the data
 * @throws AnzoException
 */
public void parseUpdates(Reader reader, final INamedGraphUpdateHandler handler) throws AnzoException {
    try {
        XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    String uri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri);
                    String uuid = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID);
                    currentNamedGraphUpdate = new NamedGraphUpdate(MemURI.create(uri));
                    if (uuid != null) {
                        currentNamedGraphUpdate.setUUID(MemURI.create(uuid));
                    }
                    String revision = parser.getAttributeValue(null, SerializationConstants.revision);
                    if (revision != null) {
                        currentNamedGraphUpdate.setRevision(Long.parseLong(revision));
                    }
                } else if (SerializationConstants.additions.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getAdditions();
                } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getMetaAdditions();
                } else if (SerializationConstants.removals.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getRemovals();
                } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getMetaRemovals();
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType);
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    nodeType = parser.getAttributeValue(null, SerializationConstants.objectType);
                    language = parser.getAttributeValue(null, SerializationConstants.language);
                    datatype = parser.getAttributeValue(null, SerializationConstants.dataType);
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    handler.handleNamedGraphUpdate(currentNamedGraphUpdate);
                    currentNamedGraphUpdate = null;
                } else if (SerializationConstants.additions.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.removals.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                    currentStatements.add(Constants.valueFactory.createStatement(currentSubject,
                            currentPredicate, currentObject, currentNamedGraphURI));
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    if (NodeType.BNODE.name().equals(nodeType)) {
                        currentSubject = Constants.valueFactory.createBNode(currentValue);
                    } else {
                        currentSubject = Constants.valueFactory.createURI(currentValue);
                    }
                    currentValue = null;
                    nodeType = null;
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                    currentPredicate = Constants.valueFactory.createURI(currentValue);
                    currentValue = null;
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    if (NodeType.BNODE.name().equals(nodeType)) {
                        currentObject = Constants.valueFactory.createBNode(currentValue);
                    } else if (NodeType.URI.name().equals(nodeType)) {
                        currentObject = Constants.valueFactory.createURI(currentValue);
                    } else if (NodeType.LITERAL.name().equals(nodeType)) {
                        if (Base64.isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) {
                            currentValue = new String(
                                    Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)),
                                    Constants.byteEncoding);
                        }
                        if (datatype != null) {
                            currentObject = Constants.valueFactory.createLiteral(currentValue,
                                    Constants.valueFactory.createURI(datatype));
                        } else if (language != null) {
                            currentObject = Constants.valueFactory.createLiteral(currentValue, language);
                        } else {
                            currentObject = Constants.valueFactory.createLiteral(currentValue);
                        }
                    }
                    currentValue = null;
                    nodeType = null;
                    language = null;
                    datatype = null;
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                    currentNamedGraphURI = Constants.valueFactory.createURI(currentValue);
                    currentValue = null;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                currentValue = parser.getText();
                break;
            case XMLStreamConstants.CDATA:
                currentValue = parser.getText();
                break;
            }
        }
        parser.close();
    } catch (XMLStreamException ex) {
        throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage());
    } catch (UnsupportedEncodingException uee) {
        throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee);
    }
}

From source file:org.openanzo.services.serialization.XMLUpdatesReader.java

/**
 * Parse the data within the reader, passing the results to the IRepositoryHandler
 * //www.  j a va  2 s.  c  o m
 * @param reader
 *            reader containing the data
 * @param handler
 *            Handler which will handle the elements within the data
 * @throws AnzoException
 */
private void parseUpdateTransactions(Reader reader, final IUpdatesHandler handler) throws AnzoException {
    try {
        XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (SerializationConstants.transaction.equals(parser.getLocalName())) {
                    currentTransaction = parseTransaction(parser);
                } else if (SerializationConstants.transactionContext.equals(parser.getLocalName())) {
                    currentStatements = currentTransaction.getTransactionContext();
                } else if (SerializationConstants.preconditions.equals(parser.getLocalName())) {
                    currentStatements = new ArrayList<Statement>();
                } else if (SerializationConstants.namedGraphUpdates.equals(parser.getLocalName())) {
                    currentValue = null;
                } else if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    String uri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri);
                    String uuid = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID);
                    currentNamedGraphUpdate = new NamedGraphUpdate(MemURI.create(uri));
                    if (uuid != null) {
                        currentNamedGraphUpdate.setUUID(MemURI.create(uuid));
                    }
                    String revision = parser.getAttributeValue(null, SerializationConstants.revision);
                    if (revision != null) {
                        currentNamedGraphUpdate.setRevision(Long.parseLong(revision));
                    }
                } else if (SerializationConstants.additions.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getAdditions();
                } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getMetaAdditions();
                } else if (SerializationConstants.removals.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getRemovals();
                } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getMetaRemovals();
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType);
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    nodeType = parser.getAttributeValue(null, SerializationConstants.objectType);
                    language = parser.getAttributeValue(null, SerializationConstants.language);
                    datatype = parser.getAttributeValue(null, SerializationConstants.dataType);
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                } else if (SerializationConstants.errorResult.equals(parser.getLocalName())) {
                    String errorCodeStr = parser.getAttributeValue(null, SerializationConstants.errorCode);
                    errorCode = Long.parseLong(errorCodeStr);
                    errorArgs = new ArrayList<String>();
                } else if (SerializationConstants.errorMessageArg.equals(parser.getLocalName())) {

                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (SerializationConstants.transaction.equals(parser.getLocalName())) {
                    handler.handleTransaction(currentTransaction);
                    currentTransaction = null;
                } else if (SerializationConstants.transactionContext.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.preconditions.equals(parser.getLocalName())) {
                    currentTransaction.getPreconditions()
                            .addAll(CommonSerializationUtils.parsePreconditionStatements(currentStatements));
                } else if (SerializationConstants.namedGraphUpdates.equals(parser.getLocalName())) {
                    if (currentValue != null)
                        currentTransaction.getUpdatedNamedGraphRevisions()
                                .putAll(CommonSerializationUtils.readNamedGraphRevisions(currentValue));
                } else if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    currentTransaction.addNamedGraphUpdate(currentNamedGraphUpdate);
                } else if (SerializationConstants.additions.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.removals.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                    currentStatements.add(Constants.valueFactory.createStatement(currentSubject,
                            currentPredicate, currentObject, currentNamedGraphURI));
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    if (NodeType.BNODE.name().equals(nodeType)) {
                        currentSubject = Constants.valueFactory.createBNode(currentValue);
                    } else {
                        currentSubject = Constants.valueFactory.createURI(currentValue);
                    }
                    currentValue = null;
                    nodeType = null;
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                    currentPredicate = Constants.valueFactory.createURI(currentValue);
                    currentValue = null;
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    if (NodeType.BNODE.name().equals(nodeType)) {
                        currentObject = Constants.valueFactory.createBNode(currentValue);
                    } else if (NodeType.URI.name().equals(nodeType)) {
                        currentObject = Constants.valueFactory.createURI(currentValue);
                    } else if (NodeType.LITERAL.name().equals(nodeType)) {
                        if (currentValue == null) {
                            currentValue = "";
                        } else if (Base64.isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) {
                            currentValue = new String(
                                    Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)),
                                    Constants.byteEncoding);
                        }
                        if (datatype != null) {
                            currentObject = Constants.valueFactory.createLiteral(currentValue,
                                    Constants.valueFactory.createURI(datatype));
                        } else if (language != null) {
                            currentObject = Constants.valueFactory.createLiteral(currentValue, language);
                        } else {
                            currentObject = Constants.valueFactory.createLiteral(currentValue);
                        }
                    }
                    currentValue = null;
                    nodeType = null;
                    language = null;
                    datatype = null;
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                    currentNamedGraphURI = Constants.valueFactory.createURI(currentValue);
                    currentValue = null;
                } else if (SerializationConstants.errorResult.equals(parser.getLocalName())) {
                    currentTransaction.getErrors()
                            .add(new AnzoException(errorCode, errorArgs.toArray(new String[0])));
                    errorCode = 0;
                    errorArgs = null;
                } else if (SerializationConstants.errorMessageArg.equals(parser.getLocalName())) {
                    errorArgs.add(currentValue);
                    currentValue = null;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                if (parser.hasText())
                    currentValue = parser.getText();
                break;
            case XMLStreamConstants.CDATA:
                if (parser.hasText())
                    currentValue = parser.getText();
                break;
            }
        }
        parser.close();
    } catch (XMLStreamException ex) {
        throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage());
    } catch (UnsupportedEncodingException uee) {
        throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee);
    }
}

From source file:org.openo.nfvo.emsdriver.collector.TaskThread.java

private boolean processCMXml(File tempfile, String nename, String type) {

    String csvpath = localPath + nename + "/" + type + "/";
    File csvpathfile = new File(csvpath);
    if (!csvpathfile.exists()) {
        csvpathfile.mkdirs();/* w w w .  j av  a 2s . c o  m*/
    }
    String csvFileName = nename + dateFormat.format(new Date()) + System.nanoTime();
    String csvpathAndFileName = csvpath + csvFileName + ".csv";
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(csvpathAndFileName, false);
        bos = new BufferedOutputStream(fos, 10240);
    } catch (FileNotFoundException e1) {
        log.error("FileNotFoundException " + StringUtil.getStackTrace(e1));
    }

    boolean FieldNameFlag = false;
    boolean FieldValueFlag = false;
    //line num
    int countNum = 0;
    String xmlPathAndFileName = null;
    String localName = null;
    String endLocalName = null;
    String rmUID = null;
    int index = -1;
    ArrayList<String> names = new ArrayList<String>();// colname
    LinkedHashMap<String, String> nameAndValue = new LinkedHashMap<String, String>();

    FileInputStream fis = null;
    InputStreamReader isr = null;
    XMLStreamReader reader = null;
    try {
        fis = new FileInputStream(tempfile);
        isr = new InputStreamReader(fis, Constant.ENCODING_UTF8);
        XMLInputFactory fac = XMLInputFactory.newInstance();
        reader = fac.createXMLStreamReader(isr);
        int event = -1;
        boolean setcolum = true;
        while (reader.hasNext()) {
            try {
                event = reader.next();
                switch (event) {
                case XMLStreamConstants.START_ELEMENT:
                    localName = reader.getLocalName();
                    if ("FieldName".equalsIgnoreCase(localName)) {
                        FieldNameFlag = true;
                    }
                    if (FieldNameFlag) {
                        if ("N".equalsIgnoreCase(localName)) {
                            String colName = reader.getElementText().trim();
                            names.add(colName);
                        }
                    }
                    if ("FieldValue".equalsIgnoreCase(localName)) {
                        FieldValueFlag = true;

                    }
                    if (FieldValueFlag) {
                        if (setcolum) {
                            xmlPathAndFileName = this.setColumnNames(nename, names, type);
                            setcolum = false;
                        }

                        if ("Object".equalsIgnoreCase(localName)) {
                            int ac = reader.getAttributeCount();
                            for (int i = 0; i < ac; i++) {
                                if ("rmUID".equalsIgnoreCase(reader.getAttributeLocalName(i))) {
                                    rmUID = reader.getAttributeValue(i).trim();
                                }
                            }
                            nameAndValue.put("rmUID", rmUID);
                        }
                        if ("V".equalsIgnoreCase(localName)) {
                            index = Integer.parseInt(reader.getAttributeValue(0)) - 1;
                            String currentName = names.get(index);
                            String v = reader.getElementText().trim();
                            nameAndValue.put(currentName, v);
                        }
                    }
                    break;
                case XMLStreamConstants.CHARACTERS:
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    endLocalName = reader.getLocalName();

                    if ("FieldName".equalsIgnoreCase(endLocalName)) {
                        FieldNameFlag = false;
                    }
                    if ("FieldValue".equalsIgnoreCase(endLocalName)) {
                        FieldValueFlag = false;
                    }
                    if ("Object".equalsIgnoreCase(endLocalName)) {
                        countNum++;
                        this.appendLine(nameAndValue, bos);
                        nameAndValue.clear();
                    }
                    break;
                }
            } catch (Exception e) {
                log.error("" + StringUtil.getStackTrace(e));
                event = reader.next();
            }
        }

        if (bos != null) {
            bos.close();
            bos = null;
        }
        if (fos != null) {
            fos.close();
            fos = null;
        }

        String[] fileKeys = this.createZipFile(csvpathAndFileName, xmlPathAndFileName, nename);
        //ftp store
        Properties ftpPro = configurationInterface.getProperties();
        String ip = ftpPro.getProperty("ftp_ip");
        String port = ftpPro.getProperty("ftp_port");
        String ftp_user = ftpPro.getProperty("ftp_user");
        String ftp_password = ftpPro.getProperty("ftp_password");

        String ftp_passive = ftpPro.getProperty("ftp_passive");
        String ftp_type = ftpPro.getProperty("ftp_type");
        String remoteFile = ftpPro.getProperty("ftp_remote_path");
        this.ftpStore(fileKeys, ip, port, ftp_user, ftp_password, ftp_passive, ftp_type, remoteFile);
        //create Message
        String message = this.createMessage(fileKeys[1], ftp_user, ftp_password, ip, port, countNum, nename);

        //set message
        this.setMessage(message);
    } catch (Exception e) {
        log.error("" + StringUtil.getStackTrace(e));
        return false;
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (bos != null) {
                bos.close();
            }

            if (fos != null) {
                fos.close();
            }
        } catch (Exception e) {
            log.error(e);
        }
    }
    return true;
}

From source file:org.orbisgis.core.layerModel.mapcatalog.RemoteMapCatalog.java

/**
 * Request the workspaces synchronously.
 * This call may take a long time to execute.
 * @return A list of workspaces/*  w  ww.  j ava  2  s.c  om*/
 * @throws IOException The request fail
 */
public List<Workspace> getWorkspaces() throws IOException {
    List<Workspace> workspaces = new ArrayList<Workspace>();
    // Construct request
    URL requestWorkspacesURL = new URL(RemoteCommons.getUrlWorkspaceList(cParams));
    // Establish connection
    HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(cParams.getConnectionTimeOut());
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException(I18N.tr("HTTP Error {0} message : {1}", connection.getResponseCode(),
                connection.getResponseMessage()));
    }

    // Read the response content
    BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection)));

    //"Content-Type" "text/xml; charset=utf-8"
    XMLInputFactory factory = XMLInputFactory.newInstance();

    // Parse Data
    XMLStreamReader parser;
    try {
        parser = factory.createXMLStreamReader(in);
        // Fill workspaces
        parseXML(workspaces, parser);
        parser.close();
    } catch (XMLStreamException ex) {
        throw new IOException(I18N.tr("Invalid XML content"), ex);
    }
    return workspaces;
}

From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java

/**
 * Add a mapcontext to the workspace//from  ww w .j  a  v a 2 s  . c o m
 * @param mapContext
 * @return The ID of the published map context
 * @throws IOException 
 */
public int publishMapContext(MapContext mapContext, Integer mapContextId) throws IOException {
    // Construct request
    URL requestWorkspacesURL;
    if (mapContextId == null) {
        // Post a new map context
        requestWorkspacesURL = new URL(RemoteCommons.getUrlPostContext(cParams, workspaceName));
    } else {
        // Update an existing map context
        requestWorkspacesURL = new URL(RemoteCommons.getUrlUpdateContext(cParams, workspaceName, mapContextId));
    }
    // Establish connection
    HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setConnectTimeout(cParams.getConnectionTimeOut());
    connection.addRequestProperty("Content-Type", "text/xml");
    OutputStream out = connection.getOutputStream();
    mapContext.write(out); // Send map context
    out.close();

    // Get response
    int responseCode = connection.getResponseCode();
    if (!((responseCode == HttpURLConnection.HTTP_CREATED && mapContextId == null)
            || (responseCode == HttpURLConnection.HTTP_OK && mapContextId != null))) {
        throw new IOException(I18N.tr("HTTP Error {0} message : {1} with the URL {2}",
                connection.getResponseCode(), connection.getResponseMessage(), requestWorkspacesURL));
    }

    if (mapContextId == null) {
        // Get response content
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),
                RemoteCommons.getConnectionCharset(connection)));

        XMLInputFactory factory = XMLInputFactory.newInstance();

        // Parse Data
        XMLStreamReader parser;
        try {
            parser = factory.createXMLStreamReader(in);
            // Fill workspaces
            int resId = parsePublishResponse(parser);
            parser.close();
            return resId;
        } catch (XMLStreamException ex) {
            throw new IOException(I18N.tr("Invalid XML content"), ex);
        }
    } else {
        return mapContextId;
    }
}

From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java

/**
 * Retrieve the list of MapContext linked with this workspace
 * This call may take a long time to execute.
 * @return/*www .ja  v  a 2  s . c o  m*/
 * @throws IOException Connection failure 
 */
public List<RemoteMapContext> getMapContextList() throws IOException {
    List<RemoteMapContext> contextList = new ArrayList<RemoteMapContext>();
    // Construct request
    URL requestWorkspacesURL = new URL(RemoteCommons.getUrlContextList(cParams, workspaceName));
    // Establish connection
    HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(cParams.getConnectionTimeOut());

    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException(I18N.tr("HTTP Error {0} message : {1}", connection.getResponseCode(),
                connection.getResponseMessage()));
    }

    XMLInputFactory factory = XMLInputFactory.newInstance();

    // Read the response content
    BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection)));

    // Parse Data
    XMLStreamReader parser;
    try {
        parser = factory.createXMLStreamReader(in);
        // Fill workspaces
        parseXML(contextList, parser);
        parser.close();
    } catch (XMLStreamException ex) {
        throw new IOException(I18N.tr("Invalid XML content"), ex);
    }
    return contextList;
}

From source file:org.osaf.cosmo.model.text.XhtmlCollectionFormat.java

public CollectionItem parse(String source, EntityFactory entityFactory) throws ParseException {
    CollectionItem collection = entityFactory.createCollection();

    try {/*www  . j av  a2  s.c  o m*/
        if (source == null)
            throw new ParseException("Source has no XML data", -1);
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inCollection = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement())
                continue;

            if (hasClass(reader, "collection")) {
                if (log.isDebugEnabled())
                    log.debug("found collection element");
                inCollection = true;
                continue;
            }

            if (inCollection && hasClass(reader, "name")) {
                if (log.isDebugEnabled())
                    log.debug("found name element");

                String name = reader.getElementText();
                if (StringUtils.isBlank(name))
                    throw new ParseException("Empty name not allowed",
                            reader.getLocation().getCharacterOffset());
                collection.setDisplayName(name);

                continue;
            }

            if (inCollection && hasClass(reader, "uuid")) {
                if (log.isDebugEnabled())
                    log.debug("found uuid element");

                String uuid = reader.getElementText();
                if (StringUtils.isBlank(uuid))
                    throw new ParseException("Empty uuid not allowed",
                            reader.getLocation().getCharacterOffset());
                collection.setUid(uuid);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return collection;
}

From source file:org.osaf.cosmo.model.text.XhtmlPreferenceFormat.java

public Preference parse(String source, EntityFactory entityFactory) throws ParseException {
    Preference pref = entityFactory.createPreference();

    try {/* www.j  a  va2s  .c om*/
        if (source == null)
            throw new ParseException("Source has no XML data", -1);
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inPreference = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement())
                continue;

            if (hasClass(reader, "preference")) {
                if (log.isDebugEnabled())
                    log.debug("found preference element");
                inPreference = true;
                continue;
            }

            if (inPreference && hasClass(reader, "key")) {
                if (log.isDebugEnabled())
                    log.debug("found key element");

                String key = reader.getElementText();
                if (StringUtils.isBlank(key))
                    handleParseException("Key element must not be empty", reader);
                pref.setKey(key);

                continue;
            }

            if (inPreference && hasClass(reader, "value")) {
                if (log.isDebugEnabled())
                    log.debug("found value element");

                String value = reader.getElementText();
                if (StringUtils.isBlank(value))
                    value = "";
                pref.setValue(value);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return pref;
}

From source file:org.osaf.cosmo.model.text.XhtmlSubscriptionFormat.java

public CollectionSubscription parse(String source, EntityFactory entityFactory) throws ParseException {
    CollectionSubscription sub = entityFactory.createCollectionSubscription();

    try {/*from   w ww .j a v  a 2  s  .c o  m*/
        if (source == null)
            throw new ParseException("Source has no XML data", -1);
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inLocalSub = false;
        boolean inCollection = false;
        boolean inTicket = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement())
                continue;

            if (hasClass(reader, "local-subscription")) {
                if (log.isDebugEnabled())
                    log.debug("found local-subscription element");
                inLocalSub = true;
                continue;
            }

            if (inLocalSub && hasClass(reader, "name")) {
                if (log.isDebugEnabled())
                    log.debug("found name element");

                String name = reader.getElementText();
                if (StringUtils.isBlank(name))
                    handleParseException("Name element must not be empty", reader);
                sub.setDisplayName(name);

                continue;
            }

            if (inLocalSub && hasClass(reader, "collection")) {
                if (log.isDebugEnabled())
                    log.debug("found collection element");
                inCollection = true;
                inTicket = false;
                continue;
            }

            if (inCollection && hasClass(reader, "uuid")) {
                if (log.isDebugEnabled())
                    log.debug("found uuid element");

                String uuid = reader.getElementText();
                if (StringUtils.isBlank(uuid))
                    handleParseException("Uuid element must not be empty", reader);
                sub.setCollectionUid(uuid);

                continue;
            }

            if (inLocalSub && hasClass(reader, "ticket")) {
                if (log.isDebugEnabled())
                    log.debug("found ticket element");
                inCollection = false;
                inTicket = true;
                continue;
            }

            if (inTicket && hasClass(reader, "key")) {
                if (log.isDebugEnabled())
                    log.debug("found key element");

                String key = reader.getElementText();
                if (StringUtils.isBlank(key))
                    handleParseException("Key element must not be empty", reader);
                sub.setTicketKey(key);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return sub;
}

From source file:org.osaf.cosmo.model.text.XhtmlTicketFormat.java

public Ticket parse(String source, EntityFactory entityFactory) throws ParseException {

    String key = null;/*  w w  w .jav  a 2  s  .  c o m*/
    TicketType type = null;
    Integer timeout = null;
    try {
        if (source == null)
            throw new ParseException("Source has no XML data", -1);
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inTicket = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement())
                continue;

            if (hasClass(reader, "ticket")) {
                if (log.isDebugEnabled())
                    log.debug("found ticket element");
                inTicket = true;
                continue;
            }

            if (inTicket && hasClass(reader, "key")) {
                if (log.isDebugEnabled())
                    log.debug("found key element");

                key = reader.getElementText();
                if (StringUtils.isBlank(key))
                    handleParseException("Key element must not be empty", reader);

                continue;
            }

            if (inTicket && hasClass(reader, "type")) {
                if (log.isDebugEnabled())
                    log.debug("found type element");

                String typeId = reader.getAttributeValue(null, "title");
                if (StringUtils.isBlank(typeId))
                    handleParseException("Ticket type title must not be empty", reader);
                type = TicketType.createInstance(typeId);

                continue;
            }
            if (inTicket && hasClass(reader, "timeout")) {
                if (log.isDebugEnabled())
                    log.debug("found timeout element");

                String timeoutString = reader.getAttributeValue(null, "title");
                if (StringUtils.isBlank(timeoutString))
                    timeout = null;
                else
                    timeout = Integer.getInteger(timeoutString);

                continue;
            }
        }
        if (type == null || key == null)
            handleParseException("Ticket must have type and key", reader);
        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    Ticket ticket = entityFactory.createTicket(type);
    ticket.setKey(key);
    if (timeout == null)
        ticket.setTimeout(Ticket.TIMEOUT_INFINITE);
    else
        ticket.setTimeout(timeout);

    return ticket;
}