Example usage for javax.xml.stream XMLStreamWriter flush

List of usage examples for javax.xml.stream XMLStreamWriter flush

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter flush.

Prototype

public void flush() throws XMLStreamException;

Source Link

Document

Write any cached data to the underlying output mechanism.

Usage

From source file:org.wso2.carbon.registry.server.mgt.test.RegistryConfiguratorTestCase.java

private void increaseSearchIndexStartTimeDelay() throws Exception {

    FileOutputStream fileOutputStream = null;
    XMLStreamWriter writer = null;
    OMElement documentElement = getRegistryXmlOmElement();
    try {/*from   w  ww. j  a va 2s.c om*/
        AXIOMXPath xpathExpression = new AXIOMXPath(
                "/wso2registry/indexingConfiguration/startingDelayInSeconds");
        OMElement indexConfigNode = (OMElement) xpathExpression.selectSingleNode(documentElement);
        indexConfigNode.setText("60");
        AXIOMXPath xpathExpression1 = new AXIOMXPath(
                "/wso2registry/indexingConfiguration/indexingFrequencyInSeconds");
        OMElement indexConfigNode1 = (OMElement) xpathExpression1.selectSingleNode(documentElement);
        indexConfigNode1.setText("30");
        fileOutputStream = new FileOutputStream(getRegistryXMLPath());
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream);
        documentElement.serialize(writer);
        documentElement.build();
        Thread.sleep(2000);

    } catch (Exception e) {
        log.error("registry.xml edit fails" + e.getMessage());
        throw new Exception("registry.xml edit fails" + e.getMessage());
    } finally {
        assert fileOutputStream != null;
        fileOutputStream.close();
        assert writer != null;
        writer.flush();
    }
}

From source file:org.wso2.carbon.registry.server.mgt.test.RegistryConfiguratorTestCase.java

/**
 * This method is used to change sso idp port due to port offsets.
 *
 * @throws Exception//from w ww  .  j a va  2 s.  c  om
 */
private void changeSsoIdpPort() throws Exception {

    FileOutputStream fileOutputStream = null;
    XMLStreamWriter writer = null;
    OMElement documentElement = getSsoIdpConfigOmElement();
    try {
        AXIOMXPath xpathExpression = new AXIOMXPath(
                "/SSOIdentityProviderConfig/ServiceProviders/ServiceProvider");
        List nodes = xpathExpression.selectNodes(documentElement);

        for (Object node : nodes) {
            OMElement nodeElement = (OMElement) node;
            AXIOMXPath xPathAssertionConsumerService = new AXIOMXPath("AssertionConsumerService");
            OMElement nodeUrlElement = (OMElement) xPathAssertionConsumerService.selectSingleNode(nodeElement);
            String newURL = nodeUrlElement.getText().replace("9443", "10343");
            nodeUrlElement.setText(newURL);
        }

        fileOutputStream = new FileOutputStream(getSsoIdpConfigXMLPath());
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream);
        documentElement.serialize(writer);
        documentElement.build();
        Thread.sleep(2000);

    } catch (Exception e) {
        log.error("sso-idp-config.xml edit fails" + e.getMessage());
        throw new Exception("sso-idp-config.xml edit fails" + e.getMessage());
    } finally {
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
        if (writer != null) {
            writer.flush();
        }
    }
}

From source file:org.wso2.carbon.registry.synchronization.operation.CheckInCommand.java

private void createDirectoryMetaElement(XMLStreamWriter xmlWriter, String filePath, String path,
        UserInputCallback callback) throws SynchronizationException, XMLStreamException {
    // first get the meta file of the directory.
    String metaDirectoryPath = filePath + File.separator + SynchronizationConstants.META_DIRECTORY;
    String metaFilePath = metaDirectoryPath + File.separator + SynchronizationConstants.META_FILE_PREFIX
            + SynchronizationConstants.META_FILE_EXTENSION;

    // confirm the existence of the meta file.
    OMElement metaElement = Utils.getOMElementFromMetaFile(metaFilePath);
    if (metaElement == null) {
        return;/*from   w  ww  . jav  a2s.  c  o  m*/
    }

    // alerting non-backward compatibility...
    String checkoutPathAttribute = metaElement.getAttributeValue(new QName("checkoutPath"));
    if (checkoutPathAttribute != null) {
        throw new SynchronizationException(MessageCode.CHECKOUT_OLD_VERSION);
    }

    // we are re-adjusting the name of the resource to make sure the file name and the resource
    // name is equal
    String resourceName = RegistryUtils.getResourceName(path);
    metaElement.addAttribute(DumpConstants.RESOURCE_NAME, resourceName, null);

    OMFactory factory = OMAbstractFactory.getOMFactory();

    OMAttribute status;
    if ((status = metaElement.getAttribute(new QName(DumpConstants.RESOURCE_STATUS))) != null) {
        if (DumpConstants.RESOURCE_ADDED.equals(status.getAttributeValue())) {
            metaElement = Utils.updateDefaultAddMetaFile(metaElement, path, username, true);
        }
    }

    if (status != null && !DumpConstants.RESOURCE_DELETED.equals(status.getAttributeValue())) {
        metaElement.removeAttribute(
                factory.createOMAttribute(DumpConstants.RESOURCE_STATUS, null, status.getAttributeValue()));
        Utils.updateMetaFile(metaFilePath, metaElement);
        metaElement.addAttribute(DumpConstants.RESOURCE_STATUS, status.getAttributeValue(), null);
    }

    // now write the meta data of the meta element to the writer (except children)
    Utils.writeMetaElement(xmlWriter, metaElement);
    if (status != null) {
        if (callback != null) {
            callback.displayMessage(new Message(MessageCode.SENT, new String[] { filePath }));
        }
        sentCount++;
        updated = true;
    }

    // now add the child element to the meta element
    xmlWriter.writeStartElement(DumpConstants.CHILDREN);

    File metaDirFile = new File(metaDirectoryPath);
    String[] metaFiles = metaDirFile.list(new FilenameFilter() {
        public boolean accept(File file, String s) {
            if (!s.equals("~.xml")) {
                return true;
            }
            return false;
        }
    });
    if (metaFiles != null) {
        for (String childMetaFileName : metaFiles) {
            String childFileName = Utils
                    .decodeFilename(childMetaFileName.substring(1, childMetaFileName.length() - 4));
            String childFilePath = metaDirFile.getParent() + File.separator + childFileName;
            createResourceMetaElement(xmlWriter, new File(childFilePath),
                    metaDirectoryPath + File.separator + childMetaFileName, path, callback);
        }
    }

    File directory = new File(filePath);
    String[] childrenNames = directory.list(new FilenameFilter() {
        public boolean accept(File file, String s) {
            if (file.isDirectory()) {
                if (s.equals(SynchronizationConstants.META_DIRECTORY)) {
                    return false;
                }
                return true;
            }
            return false;
        }
    });
    if (childrenNames != null) {
        for (String childFileName : childrenNames) {
            // Get childFileName of file or directory
            String childResourceName = Utils.decodeFilename(childFileName);

            if (childResourceName.endsWith(SynchronizationConstants.MINE_FILE_POSTFIX)
                    || childResourceName.endsWith(SynchronizationConstants.SERVER_FILE_POSTFIX)) {
                // there is an conflicts
                throw new SynchronizationException(MessageCode.RESOLVE_CONFLICTS);
            }

            String childPath = path + "/" + childResourceName;
            String childFilePath = filePath + File.separator + childFileName;
            createDirectoryMetaElement(xmlWriter, childFilePath, childPath, callback);
        }
    }

    if (status != null && DumpConstants.RESOURCE_DELETED.equals(status.getAttributeValue())) {
        FileUtils.deleteQuietly(directory);
    }

    xmlWriter.writeEndElement(); // to end children tag.
    xmlWriter.writeEndElement(); // to end resource tag.
    xmlWriter.flush();
}

From source file:org.wso2.carbon.registry.synchronization.operation.CheckInCommand.java

private void createResourceMetaElement(XMLStreamWriter xmlWriter, File resourceFile, String metaFilePath,
        String path, UserInputCallback callback) throws XMLStreamException, SynchronizationException {
    String fileName = resourceFile.getName();
    String filePath = resourceFile.getPath();
    // confirm the existence of the meta file.
    OMElement metaElement = Utils.getOMElementFromMetaFile(metaFilePath);
    if (metaElement == null) {
        return;// w  w  w  .j a va2s. c o  m
    }
    // we are re-adjusting the name of the resource to make sure the file name and the
    // resource name is equal
    metaElement.addAttribute(DumpConstants.RESOURCE_NAME, fileName, null);
    if (!silentUpdate && !ignoreConflicts) {
        // we only set the ignoreConflicts attribute if it is failing. This will enforce a
        // check for conflicts at the server side.
        metaElement.addAttribute(DumpConstants.IGNORE_CONFLICTS, "false", null);
    }

    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMAttribute status;
    if ((status = metaElement.getAttribute(new QName(DumpConstants.RESOURCE_STATUS))) != null) {
        if (DumpConstants.RESOURCE_ADDED.equals(status.getAttributeValue())) {
            metaElement = Utils.updateDefaultAddMetaFile(metaElement, path + File.separator + fileName,
                    username, false);
        } else if (DumpConstants.RESOURCE_DELETED.equals(status.getAttributeValue())) {
            FileUtils.deleteQuietly(new File(metaFilePath));
            FileUtils.deleteQuietly(resourceFile);
        }
    } else if (Utils.fileContentChanged(resourceFile)) {
        status = metaElement.addAttribute(DumpConstants.RESOURCE_STATUS, DumpConstants.RESOURCE_UPDATED, null);
    }

    if (status != null && !DumpConstants.RESOURCE_DELETED.equals(status.getAttributeValue())) {
        metaElement.removeAttribute(
                factory.createOMAttribute(DumpConstants.RESOURCE_STATUS, null, status.getAttributeValue()));
        metaElement.addAttribute("md5", Utils.getMD5(resourceFile), null);
        Utils.updateMetaFile(metaFilePath, metaElement);
        metaElement.addAttribute(DumpConstants.RESOURCE_STATUS, status.getAttributeValue(), null);
    }

    // now write the meta data of the meta element to the writer (except children)
    Utils.writeMetaElement(xmlWriter, metaElement);
    if (status != null) {
        if (callback != null) {
            callback.displayMessage(new Message(MessageCode.SENT, new String[] { filePath }));
        }
        sentCount++;
        updated = true;
    }

    // adding the content if resource is not deleted
    if (status == null
            || (status != null && !DumpConstants.RESOURCE_DELETED.equals(status.getAttributeValue()))) {
        byte[] content = Utils.getBytesFromFile(resourceFile);
        String encodedContent = Base64.encode(content);

        OMElement contentEle = factory.createOMElement(new QName(DumpConstants.CONTENT));
        OMText contentText = factory.createOMText(encodedContent);
        contentEle.addChild(contentText);
        contentEle.serialize(xmlWriter);
    }
    xmlWriter.writeEndElement(); // to end resource tag.
    xmlWriter.flush();
}

From source file:org.wso2.carbon.registry.synchronization.Utils.java

private static void addMetadata(String metaFilePath, String fileName, boolean isCollection, String registryPath,
        String registryUrl, boolean root) throws SynchronizationException {
    FileWriter writer = null;/*w  w  w . jav  a2 s  .c  o m*/
    File metaDir;
    File file = new File(metaFilePath);
    if (file.exists()) {
        return;
    }
    try {
        metaDir = new File(file.getParent());
        metaDir.mkdirs();
        file.createNewFile();
        writer = new FileWriter(file);
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter xmlWriter = xof.createXMLStreamWriter(writer);
        xmlWriter.writeStartElement("resource");
        xmlWriter.writeAttribute("name", fileName);
        xmlWriter.writeAttribute("isCollection", String.valueOf(isCollection));
        xmlWriter.writeAttribute("path", registryPath);
        if (registryUrl != null) {
            xmlWriter.writeAttribute("registryUrl", registryUrl);
        }
        xmlWriter.writeAttribute("status", "added");
        xmlWriter.writeEndElement();
        xmlWriter.flush();
    } catch (Exception e) {
        throw new SynchronizationException(MessageCode.ERROR_IN_ADDING_METADATA);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("Failed to close the stream", e);
            }
        }
    }
}

From source file:org.wso2.carbon.registry.synchronization.Utils.java

private static void setDelete(String metaFilePath) throws SynchronizationException {
    File metaFile = new File(metaFilePath);
    OMElement resourceElement;/*ww w. j  a  v a  2s .  c o  m*/
    FileWriter writer = null;
    try {
        resourceElement = new StAXOMBuilder(new FileInputStream(metaFile)).getDocumentElement();
        resourceElement.addAttribute("status", "deleted", null);
        writer = new FileWriter(metaFile);
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter xmlWriter = xof.createXMLStreamWriter(writer);
        resourceElement.serialize(xmlWriter);
        xmlWriter.flush();

    } catch (FileNotFoundException e) {
        throw new SynchronizationException(MessageCode.RESOURCE_NOT_UNDER_REGISTRY_CONTROL);
    } catch (Exception e) {
        throw new SynchronizationException(MessageCode.RESOURCE_METADATA_CORRUPTED);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("Failed to close the stream", e);
            }
        }
    }
}

From source file:org.wso2.carbon.reporting.template.core.handler.metadata.AbstractMetaDataHandler.java

private void saveTempfile() {
    try {//  w  w  w  . ja  va2 s .  co  m
        File file = new File("metadata.xml");
        FileWriter fstream = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fstream);
        XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
        reportsElement.serialize(writer, true);
        writer.flush();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
}

From source file:org.wso2.carbon.repository.core.ResourceStorer.java

private void dumpRecursively(String path, XMLStreamWriter xmlWriter, Writer writer)
        throws RepositoryException, XMLStreamException {
    // adding resource meta data
    ResourceImpl resource = resourceDAO.getResourceMetaData(path);

    if (resource == null) {
        return;//from ww w  .  ja  v a2  s. co  m
    }

    xmlWriter.writeStartElement(DumpConstants.RESOURCE);

    // adding path as an attribute, updated dump has name instead of path
    xmlWriter.writeAttribute(DumpConstants.RESOURCE_NAME, RepositoryUtils.getResourceName(path));

    //adding dump attribute
    xmlWriter.writeAttribute(DumpConstants.RESOURCE_STATUS, DumpConstants.RESOURCE_DUMP);

    // adding isCollection as an attribute
    xmlWriter.writeAttribute(DumpConstants.RESOURCE_IS_COLLECTION,
            (resource instanceof CollectionImpl) ? DumpConstants.RESOURCE_IS_COLLECTION_TRUE
                    : DumpConstants.RESOURCE_IS_COLLECTION_FALSE);

    // set media type
    String mediaType = resource.getMediaType();

    xmlWriter.writeStartElement(DumpConstants.MEDIA_TYPE);
    xmlWriter.writeCharacters(mediaType != null ? mediaType : "");
    xmlWriter.writeEndElement();

    // set version
    long version = resource.getVersionNumber();

    xmlWriter.writeStartElement(DumpConstants.VERSION);
    xmlWriter.writeCharacters(Long.toString(version) != null ? Long.toString(version) : "");
    xmlWriter.writeEndElement();

    // set creator
    String creator = resource.getAuthorUserName();

    xmlWriter.writeStartElement(DumpConstants.CREATOR);
    xmlWriter.writeCharacters(creator != null ? creator : "");
    xmlWriter.writeEndElement();

    // set createdTime
    Date createdTime = resource.getCreatedTime();

    xmlWriter.writeStartElement(DumpConstants.CREATED_TIME);
    xmlWriter.writeCharacters(
            Long.toString(createdTime.getTime()) != null ? Long.toString(createdTime.getTime()) : "");
    xmlWriter.writeEndElement();

    // set updater
    String updater = resource.getLastUpdaterUserName();

    xmlWriter.writeStartElement(DumpConstants.LAST_UPDATER);
    xmlWriter.writeCharacters(updater != null ? updater : "");
    xmlWriter.writeEndElement();

    // set LastModified
    Date lastModified = resource.getLastModified();

    xmlWriter.writeStartElement(DumpConstants.LAST_MODIFIED);
    xmlWriter.writeCharacters(
            Long.toString(lastModified.getTime()) != null ? Long.toString(lastModified.getTime()) : "");
    xmlWriter.writeEndElement();

    // set UUID
    String uuid = resource.getUUID();

    xmlWriter.writeStartElement(DumpConstants.UUID);
    xmlWriter.writeCharacters(uuid != null ? uuid : "");
    xmlWriter.writeEndElement();

    // set Description
    String description = resource.getDescription();

    xmlWriter.writeStartElement(DumpConstants.DESCRIPTION);
    xmlWriter.writeCharacters(description != null ? description : "");
    xmlWriter.writeEndElement();

    // fill properties
    resourceDAO.fillResourceProperties(resource);
    xmlWriter.writeStartElement(DumpConstants.PROPERTIES);

    for (Object keyObject : resource.getPropertyKeys()) {
        String key = (String) keyObject;
        List<String> propValues = resource.getPropertyValues(key);
        for (String value : propValues) {
            xmlWriter.writeStartElement(DumpConstants.PROPERTY_ENTRY);
            // adding the key and value as attributes

            xmlWriter.writeAttribute(DumpConstants.PROPERTY_ENTRY_KEY, key);

            if (value != null) {
                xmlWriter.writeCharacters(value != null ? value : "");
            }

            xmlWriter.writeEndElement();
        }
    }
    xmlWriter.writeEndElement();

    // adding contents..
    if (!(resource instanceof CollectionImpl)) {
        resourceDAO.fillResourceContent(resource);

        byte[] content = (byte[]) resource.getContent();
        if (content != null) {
            xmlWriter.writeStartElement(DumpConstants.CONTENT);
            xmlWriter.writeCharacters(DatatypeConverter.printBase64Binary(content) != null
                    ? DatatypeConverter.printBase64Binary(content)
                    : "");
            xmlWriter.writeEndElement();
        }
    }

    // getting children and applying dump recursively
    if (resource instanceof CollectionImpl) {
        CollectionImpl collection = (CollectionImpl) resource;
        resourceDAO.fillChildren(collection, 0, -1);
        String childPaths[] = collection.getChildPaths();

        xmlWriter.writeStartElement(DumpConstants.CHILDREN);
        xmlWriter.writeCharacters("");

        xmlWriter.flush();

        for (String childPath : childPaths) {
            // we would be writing the start element of the child and its name here.
            try {
                String resourceName = RepositoryUtils.getResourceName(childPath);
                writer.write("<resource name=\"" + resourceName + "\"");
                writer.flush();
            } catch (IOException e) {
                String msg = "Error in writing the start element for the path: " + childPath + ".";
                log.error(msg, e);
                throw new RepositoryException(msg, e);
            }

            recursionRepository.dumpRecursively(childPath, new DumpWriter(writer));
        }
        xmlWriter.writeEndElement();
    }

    xmlWriter.writeEndElement();
    xmlWriter.flush();
}

From source file:org.wso2.carbon.security.config.SecurityConfigAdmin.java

private OMElement buildRampartConfigXML(String privateStore, String[] trustedStores,
        KerberosConfigData kerberosConfig) throws SecurityConfigException {

    ByteArrayOutputStream out = null;
    XMLStreamWriter writer = null;
    OMElement rampartConfigElement = null;
    try {/*from   ww  w .j a va  2  s. c  om*/
        Properties props = getServerCryptoProperties(privateStore, trustedStores);
        RampartConfig rampartConfig = new RampartConfig();
        populateRampartConfig(rampartConfig, props, kerberosConfig);
        if (rampartConfig != null) {
            //addRampartConfigs(policyElement, rampartConfig);
            out = new ByteArrayOutputStream();
            writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
            rampartConfig.serialize(writer);
            writer.flush();
            writer.close();
            out.close();
            out.flush();
            rampartConfigElement = AXIOMUtil.stringToOM(out.toString());
        }
    } catch (Exception e) {
        throw new SecurityConfigException("Error while building rampart configs", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error("Error while closing output stream", e);
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (XMLStreamException e) {
                    log.error("Error while closing xml stream writer", e);
                }
            }
        }
    }
    return rampartConfigElement;
}

From source file:org.wso2.dss.integration.test.samples.EventingSampleTestCase.java

private void updateAxis2_ClientXML() throws Exception {
    String axis2_client_path = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator
            + "conf" + File.separator + "axis2" + File.separator + "axis2_client.xml";

    String mail_transport_config = getResourceLocation() + File.separator + "resources" + File.separator
            + "mailTransport.xml";

    FileOutputStream fileOutputStream = null;
    XMLStreamWriter writer = null;

    try {//  w  ww  .j  a v a  2s. c om
        OMElement axis2_client_xml = AXIOMUtil.stringToOM(FileManager.readFile(axis2_client_path));

        axis2_client_xml.addChild(AXIOMUtil.stringToOM(FileManager.readFile(mail_transport_config)));
        axis2_client_xml.build();
        fileOutputStream = new FileOutputStream(axis2_client_path);
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream);
        axis2_client_xml.serialize(writer);

    } catch (Exception e) {
        throw new Exception("axis2_client.xml update fails");
    } finally {
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
        if (writer != null) {
            writer.flush();
        }
    }
}