Example usage for javax.xml.stream XMLInputFactory createXMLStreamReader

List of usage examples for javax.xml.stream XMLInputFactory createXMLStreamReader

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory createXMLStreamReader.

Prototype

public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream) throws XMLStreamException;

Source Link

Document

Create a new XMLStreamReader from a java.io.InputStream

Usage

From source file:org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeManager.java

@Override
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
    Resource resource;//  w w  w .  jav a 2  s  . c om
    try {
        resource = DeviceTypeUtils.getRegistryResource(deviceType);
        if (resource != null) {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader reader = factory
                    .createXMLStreamReader(new StringReader(new String((byte[]) resource.getContent(),
                            Charset.forName(DeviceTypePluginConstants.CHARSET_UTF8))));

            JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (PlatformConfiguration) unmarshaller.unmarshal(reader);
        } else if (defaultPlatformConfiguration != null) {
            return defaultPlatformConfiguration;
        }
        return null;
    } catch (DeviceTypeMgtPluginException e) {
        throw new DeviceManagementException(
                "Error occurred while retrieving the Registry instance : " + e.getMessage(), e);
    } catch (JAXBException | XMLStreamException e) {
        throw new DeviceManagementException(
                "Error occurred while parsing the " + deviceType + " configuration : " + e.getMessage(), e);
    } catch (RegistryException e) {
        throw new DeviceManagementException("Error occurred while retrieving the Registry resource of "
                + deviceType + " Configuration : " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.device.mgt.mobile.android.impl.AndroidDeviceManager.java

@Override
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
    Resource resource;/*from  w ww.  j  ava 2s  .  c  o  m*/
    try {
        String androidRegPath = MobileDeviceManagementUtil
                .getPlatformConfigPath(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
        resource = MobileDeviceManagementUtil.getRegistryResource(androidRegPath);
        if (resource != null) {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader reader = factory
                    .createXMLStreamReader(new StringReader(new String((byte[]) resource.getContent(),
                            Charset.forName(AndroidPluginConstants.MobilePluginConstants.CHARSET_UTF8))));
            JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (PlatformConfiguration) unmarshaller.unmarshal(reader);
        }
        return null;
    } catch (AndroidDeviceMgtPluginException e) {
        throw new DeviceManagementException(
                "Error occurred while retrieving the Registry instance : " + e.getMessage(), e);
    } catch (JAXBException | XMLStreamException e) {
        throw new DeviceManagementException(
                "Error occurred while parsing the Android configuration : " + e.getMessage(), e);
    } catch (RegistryException e) {
        throw new DeviceManagementException(
                "Error occurred while retrieving the Registry resource of Android Configuration : "
                        + e.getMessage(),
                e);
    }
}

From source file:org.wso2.carbon.event.processor.storm.StormProcessorDeployer.java

private OMElement getExecutionPlanOMElement(File executionPlanFile) throws DeploymentException {
    OMElement executionPlanElement;/*from  ww w  .  ja va  2s.c  o  m*/
    BufferedInputStream inputStream = null;
    try {
        inputStream = new BufferedInputStream(new FileInputStream(executionPlanFile));
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader parser = xif.createXMLStreamReader(inputStream);
        xif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE); //for CDATA
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        executionPlanElement = builder.getDocumentElement();
        executionPlanElement.build();

    } catch (FileNotFoundException e) {
        String errorMessage = "file cannot be found : " + executionPlanFile.getName();
        log.error(errorMessage, e);
        throw new DeploymentException(errorMessage, e);
    } catch (XMLStreamException e) {
        String errorMessage = "Invalid XML for " + executionPlanFile.getName();
        log.error(errorMessage, e);
        throw new DeploymentException(errorMessage, e);
    } catch (OMException e) {
        String errorMessage = "XML tags are not properly closed in " + executionPlanFile.getName();
        log.error(errorMessage, e);
        throw new DeploymentException(errorMessage, e);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            String errorMessage = "Can not close the input stream";
            log.error(errorMessage, e);
        }
    }
    return executionPlanElement;
}

From source file:org.wso2.carbon.governance.api.endpoints.dataobjects.EndpointImpl.java

public OMElement buildOMElement(String content) throws GovernanceException {
    XMLStreamReader parser;/*from   w  w  w  . jav  a2 s  . c om*/
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, new Boolean(true));
        parser = factory.createXMLStreamReader(new StringReader(content));
    } catch (XMLStreamException e) {
        String msg = "Error in initializing the parser to build the OMElement.";
        log.error(msg, e);
        throw new GovernanceException(msg, e);
    }

    //create the builder
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    //get the root element (in this case the envelope)

    return builder.getDocumentElement();
}

From source file:org.wso2.carbon.governance.api.generic.GenericArtifactManager.java

/**
 * Creates a new artifact from the given string content.
 *
 * @param omContent the artifact content in string
 *
 * @return the artifact added./*  w w w .  j a  v  a 2 s. c  om*/
 * @throws GovernanceException if the operation failed.
 */
public GenericArtifact newGovernanceArtifact(String omContent) throws GovernanceException {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_COALESCING, true);

    try {
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(omContent));
        GenericArtifact artifact = this.newGovernanceArtifact(new StAXOMBuilder(reader).getDocumentElement());
        artifact.setContent(omContent.getBytes());

        return artifact;
    } catch (XMLStreamException e) {
        String message = "Error in creating the content from the parameters.";
        log.error(message, e);
        throw new GovernanceException(message, e);
    }
}

From source file:org.wso2.carbon.governance.api.util.GovernanceUtils.java

/**
 * Method to build an AXIOM element from a byte stream.
 *
 * @param content the stream of bytes./*from   ww w.j  a  va2s . c o  m*/
 * @return the AXIOM element.
 * @throws GovernanceException if the operation failed.
 */
public static OMElement buildOMElement(byte[] content) throws RegistryException {
    XMLStreamReader parser;
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, new Boolean(true));
        parser = factory.createXMLStreamReader(new StringReader(RegistryUtils.decodeBytes(content)));
    } catch (XMLStreamException e) {
        String msg = "Error in initializing the parser to build the OMElement.";
        log.error(msg, e);
        throw new GovernanceException(msg, e);
    }

    //create the builder
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    //get the root element (in this case the envelope)

    return builder.getDocumentElement();
}

From source file:org.wso2.carbon.governance.generic.services.ManageGenericArtifactService.java

public String addArtifact(String key, String info, String lifecycleAttribute) throws RegistryException {
    RegistryUtils.recordStatistics(key, info, lifecycleAttribute);
    Registry registry = getGovernanceUserRegistry();
    if (RegistryUtils.isRegistryReadOnly(registry.getRegistryContext())) {
        return null;
    }/*from  www.ja  v  a  2  s  . c om*/
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, true);
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(info));

        GenericArtifactManager manager = new GenericArtifactManager(registry, key);
        GenericArtifact artifact = manager
                .newGovernanceArtifact(new StAXOMBuilder(reader).getDocumentElement());

        // want to save original content, so set content here
        artifact.setContent(info.getBytes());
        artifact.setAttribute("resource.source", "AdminConsole");
        manager.addGenericArtifact(artifact);
        if (lifecycleAttribute != null) {
            String lifecycle = artifact.getAttribute(lifecycleAttribute);
            if (lifecycle != null) {
                artifact.attachLifecycle(lifecycle);
            }
        }
        return RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + artifact.getPath();
    } catch (Exception e) {
        String msg = "Unable to add artifact. ";
        if (e instanceof RegistryException) {
            throw (RegistryException) e;
        } else if (e instanceof OMException) {
            msg += "Unexpected character found in input-field name.";
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }
        throw new RegistryException(
                msg + (e.getCause() instanceof SQLException ? "" : e.getCause().getMessage()), e);
    }
}

From source file:org.wso2.carbon.governance.generic.services.ManageGenericArtifactService.java

public ArtifactsBean listArtifacts(String key, String criteria) {
    RegistryUtils.recordStatistics(key, criteria);
    UserRegistry governanceRegistry = (UserRegistry) getGovernanceUserRegistry();
    ArtifactsBean bean = new ArtifactsBean();
    try {/* ww  w . j a  v  a  2  s.  co  m*/
        final GovernanceArtifactConfiguration configuration = loadAndFindGovernanceArtifactConfiguration(key,
                getRootRegistry());
        GenericArtifactManager manager = new GenericArtifactManager(governanceRegistry,
                configuration.getMediaType(), configuration.getArtifactNameAttribute(),
                configuration.getArtifactNamespaceAttribute(), configuration.getArtifactElementRoot(),
                configuration.getArtifactElementNamespace(), configuration.getPathExpression(),
                configuration.getRelationshipDefinitions());
        final GenericArtifact referenceArtifact;
        if (criteria != null) {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            factory.setProperty(XMLInputFactory.IS_COALESCING, true);
            XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(criteria));
            referenceArtifact = manager.newGovernanceArtifact(new StAXOMBuilder(reader).getDocumentElement());
        } else {
            referenceArtifact = null;
        }

        bean.setNames(configuration.getNamesOnListUI());
        bean.setTypes(configuration.getTypesOnListUI());
        bean.setKeys(configuration.getKeysOnListUI());
        String[] expressions = configuration.getExpressionsOnListUI();
        String[] keys = configuration.getKeysOnListUI();
        List<GovernanceArtifact> artifacts = new LinkedList<GovernanceArtifact>();
        artifacts.addAll(
                Arrays.asList(manager.findGenericArtifacts(getFieldsList(referenceArtifact, configuration))));
        List<ArtifactBean> artifactBeans = new LinkedList<ArtifactBean>();
        for (GovernanceArtifact artifact : artifacts) {
            int kk = 0;
            ArtifactBean artifactBean = new ArtifactBean();
            List<String> paths = new ArrayList<String>();
            List<String> values = new ArrayList<String>();
            String path = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
                    + ((GenericArtifactImpl) artifact).getArtifactPath();
            artifactBean.setPath(path);
            for (int i = 0; i < expressions.length; i++) {
                if (expressions[i] != null) {
                    if (expressions[i].contains("@{storagePath}")
                            && ((GenericArtifactImpl) artifact).getArtifactPath() != null) {
                        paths.add(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
                                + GovernanceUtils.getPathFromPathExpression(expressions[i], artifact,
                                        ((GenericArtifactImpl) artifact).getArtifactPath()));
                    } else {
                        if ("link".equals(bean.getTypes()[i])) {
                            paths.add(GovernanceUtils.getPathFromPathExpression(expressions[i], artifact,
                                    configuration.getPathExpression()));
                        } else {
                            paths.add(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
                                    + GovernanceUtils.getPathFromPathExpression(expressions[i], artifact,
                                            configuration.getPathExpression()));
                        }
                    }
                } else {
                    paths.add("");
                }
            }
            artifactBean.setValuesB(paths.toArray(new String[paths.size()]));
            for (String keyForValue : keys) {
                if (keyForValue != null) {
                    values.add(artifact.getAttribute(keyForValue));
                } else {
                    values.add("");
                }
            }
            artifactBean.setValuesA(values.toArray(new String[values.size()]));
            artifactBean.setCanDelete(governanceRegistry.getUserRealm().getAuthorizationManager()
                    .isUserAuthorized(governanceRegistry.getUserName(), path, ActionConstants.DELETE));
            artifactBean.setLCName(((GenericArtifactImpl) artifact).getLcName());
            artifactBean.setLCState(((GenericArtifactImpl) artifact).getLcState());

            artifactBean.setCreatedDate(governanceRegistry
                    .get(((GenericArtifactImpl) artifact).getArtifactPath()).getCreatedTime());
            artifactBean.setLastUpdatedDate(governanceRegistry
                    .get(((GenericArtifactImpl) artifact).getArtifactPath()).getLastModified());
            artifactBean.setCreatedBy(governanceRegistry.get(((GenericArtifactImpl) artifact).getArtifactPath())
                    .getAuthorUserName());
            artifactBean.setLastUpdatedBy(governanceRegistry
                    .get(((GenericArtifactImpl) artifact).getArtifactPath()).getLastUpdaterUserName());

            artifactBeans.add(artifactBean);
        }
        bean.setArtifacts(artifactBeans.toArray(new ArtifactBean[artifactBeans.size()]));
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        log.error("An error occurred while obtaining the list of artifacts.", e);
    }
    return bean;
}

From source file:org.wso2.carbon.governance.generic.services.ManageGenericArtifactService.java

public String editArtifact(String path, String key, String info, String lifecycleAttribute)
        throws RegistryException {
    RegistryUtils.recordStatistics(path, key, info, lifecycleAttribute);
    Registry registry = getGovernanceUserRegistry();
    if (RegistryUtils.isRegistryReadOnly(registry.getRegistryContext())) {
        return null;
    }//w ww  .j a  va 2  s  .  c o  m
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, true);
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(info));

        GovernanceArtifactConfiguration configuration = loadAndFindGovernanceArtifactConfiguration(key,
                getRootRegistry());

        GenericArtifactManager manager = new GenericArtifactManager(registry, key);
        GenericArtifact artifact = manager
                .newGovernanceArtifact(new StAXOMBuilder(reader).getDocumentElement());
        String currentPath;
        if (path != null && path.length() > 0) {
            currentPath = path.substring(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH.length());
        } else {
            currentPath = GovernanceUtils.getPathFromPathExpression(configuration.getPathExpression(),
                    artifact);
        }
        if (registry.resourceExists(currentPath)) {
            GovernanceArtifact oldArtifact = GovernanceUtils.retrieveGovernanceArtifactByPath(registry,
                    currentPath);
            if (!(oldArtifact instanceof GovernanceArtifact)) {
                String msg = "The updated path is occupied by a non-generic artifact. path: " + currentPath
                        + ".";
                log.error(msg);
                throw new Exception(msg);
            }
            artifact.setId(oldArtifact.getId());

            // want to save original content 
            artifact.setContent(info.getBytes());

            manager.updateGenericArtifact(artifact);
        } else {
            manager.addGenericArtifact(artifact);
        }
        if (lifecycleAttribute != null && !lifecycleAttribute.equals("null")) {
            String lifecycle = artifact.getAttribute(lifecycleAttribute);
            artifact.attachLifecycle(lifecycle);
        }
        return RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + artifact.getPath();
    } catch (Exception e) {
        String msg = "Unable to edit artifact. ";
        if (e instanceof RegistryException) {
            throw (RegistryException) e;
        } else if (e instanceof OMException) {
            msg += "Unexpected character found in input-field name.";
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }
        throw new RegistryException(
                msg + (e.getCause() instanceof SQLException ? "" : e.getCause().getMessage()), e);
    }
}

From source file:org.wso2.carbon.governance.metadata.provider.util.Util.java

public static OMElement buildOMElement(byte[] content) throws MetadataException {
    XMLStreamReader parser;/* w  w w  . java  2 s  . co m*/
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, new Boolean(true));
        parser = factory.createXMLStreamReader(new StringReader(RegistryUtils.decodeBytes(content)));
    } catch (Exception e) {
        String msg = "Error in initializing the parser to build the OMElement.";
        log.error(msg, e);
        throw new MetadataException("", e);
    }

    //create the builder
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    //get the root element (in this case the envelope)

    return builder.getDocumentElement();
}