Example usage for org.xml.sax InputSource setCharacterStream

List of usage examples for org.xml.sax InputSource setCharacterStream

Introduction

In this page you can find the example usage for org.xml.sax InputSource setCharacterStream.

Prototype

public void setCharacterStream(Reader characterStream) 

Source Link

Document

Set the character stream for this input source.

Usage

From source file:org.eclipse.winery.repository.resources.artifacts.GenericArtifactsResource.java

/**
 * @return TImplementationArtifact | TDeploymentArtifact (XML) | URL of generated IA zip (in case of autoGenerateIA)
 *///from   www.  j a v a2  s. co m
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_XML)
@RestDoc(methodDescription = "Creates a new implementation/deployment artifact. "
        + "If an implementation artifact with the same name already exists, it is <em>overridden</em>.")
@SuppressWarnings("unchecked")
public Response onPost(
        @FormParam("artifactName") @RestDocParam(description = "This is the name of the implementation/deployment artifact. "
                + "Is <em>also</em>used as prefix of the name of the corresponding artifact template if no specific template is provided. "
                + "In contrast to CS01, we require a artifactName also for the implementationArtifact to be able to properly referencing it.") String artifactNameStr,

        @FormParam("artifactTemplate") @RestDocParam(description = "QName of the artifact Template - used by Winery Backend instead of artifactTemplateName + artifactTemplateNS") String artifactTemplate,

        @FormParam("artifactTemplateName") @RestDocParam(description = "if provided and autoCreateArtifactTemplate, a template of this id localname and artifactTemplateNS generated. "
                + "Winery always sends this string if auto creation is desired.") String artifactTemplateName,

        @FormParam("artifactTemplateNS") String artifactTemplateNS,

        @FormParam("autoCreateArtifactTemplate") @RestDocParam(description = "if empty, no, or false, no artifact template is created. "
                + "An artifact type has to be given in that case. "
                + "Furthermore, an artifact template name + artifact template namespace has to be provided. "
                + "Otherwise, the artifactNameStr is used as name for the artifact and a <em>new</em> artifact template is created having {@code <artifactNameString>Template} as name") String autoCreateArtifactTemplate,

        @FormParam("artifactType") @RestDocParam(description = "QName of the type, format: {namespace}localname. "
                + "Optional if artifactTemplateName + artifactTempalteNS is provided") String artifactTypeStr,

        @FormParam("artifactSpecificContent") @RestDocParam(description = "<em>XML</em> snippet that should be put inside the artifact XML in the TOSCA serialization. "
                + "This feature will be removed soon. "
                + "TODO: This only works if there is a single child element expected and not several elements. "
                + "Future versions of the Winery will support arbitrary content there.") String artifactSpecificContent,

        @FormParam("interfaceName") String interfaceNameStr,

        @FormParam("operationName") String operationNameStr,

        @FormParam("autoGenerateIA") @RestDocParam(description = "If not empty, the IA generator will be called") String autoGenerateIA,

        @FormParam("javapackage") @RestDocParam(description = "The Java package to use for IA generation") String javapackage,

        @Context UriInfo uriInfo) {
    // we assume that the parent ComponentInstance container exists

    // @formatter:on

    if (StringUtils.isEmpty(artifactNameStr)) {
        return Response.status(Status.BAD_REQUEST).entity("Empty artifactName").build();
    }
    if (StringUtils.isEmpty(artifactTypeStr)) {
        if (StringUtils.isEmpty(artifactTemplateName) || StringUtils.isEmpty(artifactTemplateNS)) {
            if (StringUtils.isEmpty(artifactTemplate)) {
                return Response.status(Status.BAD_REQUEST)
                        .entity("No artifact type given and no template given. Cannot guess artifact type")
                        .build();
            }
        }
    }

    if (!StringUtils.isEmpty(autoGenerateIA)) {
        if (StringUtils.isEmpty(javapackage)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("no java package name supplied for IA auto generation.").build();
        }
        if (StringUtils.isEmpty(interfaceNameStr)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("no interface name supplied for IA auto generation.").build();
        }
    }

    // convert second calling form to first calling form
    if (!StringUtils.isEmpty(artifactTemplate)) {
        QName qname = QName.valueOf(artifactTemplate);
        artifactTemplateName = qname.getLocalPart();
        artifactTemplateNS = qname.getNamespaceURI();
    }

    Document doc = null;

    // check artifact specific content for validity
    // if invalid, abort and do not create anything
    if (!StringUtils.isEmpty(artifactSpecificContent)) {
        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            StringReader sr = new StringReader(artifactSpecificContent);
            is.setCharacterStream(sr);
            doc = db.parse(is);
        } catch (Exception e) {
            // FIXME: currently we allow a single element only. However, the content should be internally wrapped by an (arbitrary) XML element as the content will be nested in the artifact element, too
            GenericArtifactsResource.logger.debug("Invalid content", e);
            return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
        }
    }

    // determine artifactTemplate and artifactType

    ArtifactTypeId artifactTypeId;
    ArtifactTemplateId artifactTemplateId = null;
    ArtifactTemplateResource artifactTemplateResource = null;

    boolean doAutoCreateArtifactTemplate = !(StringUtils.isEmpty(autoCreateArtifactTemplate)
            || autoCreateArtifactTemplate.equalsIgnoreCase("no")
            || autoCreateArtifactTemplate.equalsIgnoreCase("false"));
    if (!doAutoCreateArtifactTemplate) {
        // no auto creation
        if (!StringUtils.isEmpty(artifactTemplateName) && !StringUtils.isEmpty(artifactTemplateNS)) {
            QName artifactTemplateQName = new QName(artifactTemplateNS, artifactTemplateName);
            artifactTemplateId = BackendUtils.getTOSCAcomponentId(ArtifactTemplateId.class,
                    artifactTemplateQName);
        }
        if (StringUtils.isEmpty(artifactTypeStr)) {
            // derive the type from the artifact template
            if (artifactTemplateId == null) {
                return Response.status(Status.NOT_ACCEPTABLE).entity(
                        "No artifactTemplate and no artifactType provided. Deriving the artifactType is not possible.")
                        .build();
            }
            artifactTemplateResource = new ArtifactTemplateResource(artifactTemplateId);
            artifactTypeId = BackendUtils.getTOSCAcomponentId(ArtifactTypeId.class,
                    artifactTemplateResource.getType());
        } else {
            // artifactTypeStr is directly given, use that
            artifactTypeId = BackendUtils.getTOSCAcomponentId(ArtifactTypeId.class, artifactTypeStr);
        }
    } else {
        // do the artifact template auto creation magic

        if (StringUtils.isEmpty(artifactTypeStr)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("Artifact template auto creation requested, but no artifact type supplied.")
                    .build();
        }

        // we assume that the type points to a valid artifact type
        artifactTypeId = BackendUtils.getTOSCAcomponentId(ArtifactTypeId.class, artifactTypeStr);

        if (StringUtils.isEmpty(artifactTemplateName) || StringUtils.isEmpty(artifactTemplateNS)) {
            // no explicit name provided
            // we use the artifactNameStr as prefix for the
            // artifact template name

            // we create a new artifact template in the namespace of the parent
            // element
            Namespace namespace = this.resWithNamespace.getNamespace();

            artifactTemplateId = new ArtifactTemplateId(namespace,
                    new XMLId(artifactNameStr + "artifactTemplate", false));
        } else {
            QName artifactTemplateQName = new QName(artifactTemplateNS, artifactTemplateName);
            artifactTemplateId = new ArtifactTemplateId(artifactTemplateQName);
        }
        ResourceCreationResult creationResult = BackendUtils.create(artifactTemplateId);
        if (!creationResult.isSuccess()) {
            // something went wrong. skip
            return creationResult.getResponse();
        }

        // associate the type to the created artifact template
        artifactTemplateResource = new ArtifactTemplateResource(artifactTemplateId);
        // set the type. The resource is automatically persisted inside
        artifactTemplateResource.setType(artifactTypeStr);
    }

    // variable artifactTypeId is set
    // variable artifactTemplateId is not null if artifactTemplate has been generated

    // we have to generate the DA/IA resource now
    // Doing it here instead of doing it at the subclasses is dirty on the
    // one hand, but quicker to implement on the other hand

    // Create the artifact itself

    ArtifactT resultingArtifact;

    if (this instanceof ImplementationArtifactsResource) {
        ImplementationArtifact a = new ImplementationArtifact();
        // Winery internal id is the name of the artifact:
        // store the name
        a.setName(artifactNameStr);
        a.setInterfaceName(interfaceNameStr);
        a.setOperationName(operationNameStr);
        assert (artifactTypeId != null);
        a.setArtifactType(artifactTypeId.getQName());
        if (artifactTemplateId != null) {
            a.setArtifactRef(artifactTemplateId.getQName());
        }
        if (doc != null) {
            // the content has been checked for validity at the beginning of the method.
            // If this point in the code is reached, the XML has been parsed into doc
            // just copy over the dom node. Hopefully, that works...
            a.getAny().add(doc.getDocumentElement());
        }

        this.list.add((ArtifactT) a);
        resultingArtifact = (ArtifactT) a;
    } else {
        // for comments see other branch

        TDeploymentArtifact a = new TDeploymentArtifact();
        a.setName(artifactNameStr);
        assert (artifactTypeId != null);
        a.setArtifactType(artifactTypeId.getQName());
        if (artifactTemplateId != null) {
            a.setArtifactRef(artifactTemplateId.getQName());
        }
        if (doc != null) {
            a.getAny().add(doc.getDocumentElement());
        }

        this.list.add((ArtifactT) a);
        resultingArtifact = (ArtifactT) a;
    }

    Response persistResponse = BackendUtils.persist(super.res);
    // TODO: check for error and in case one found return that

    if (StringUtils.isEmpty(autoGenerateIA)) {
        // no IA generation
        // we include an XML for the data table

        String implOrDeplArtifactXML = Utils.getXMLAsString(resultingArtifact);

        return Response.created(Utils.createURI(Util.URLencode(artifactNameStr))).entity(implOrDeplArtifactXML)
                .build();
    } else {
        // after everything was created, we fire up the artifact generation
        return this.generateImplementationArtifact(interfaceNameStr, javapackage, uriInfo, artifactTemplateId,
                artifactTemplateResource);
    }
}

From source file:org.eclipse.winery.repository.rest.resources.artifacts.GenericArtifactsResource.java

/**
 * @return TImplementationArtifact | TDeploymentArtifact (XML) | URL of generated IA zip (in case of autoGenerateIA)
 *//*from  w w w.j  av  a2 s  .  com*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Creates a new implementation/deployment artifact. If an implementation artifact with the same name already exists, it is <em>overridden</em>.")
@SuppressWarnings("unchecked")
public Response generateArtifact(GenerateArtifactApiData apiData, @Context UriInfo uriInfo) {
    // we assume that the parent ComponentInstance container exists

    final IRepository repository = RepositoryFactory.getRepository();

    if (StringUtils.isEmpty(apiData.artifactName)) {
        return Response.status(Status.BAD_REQUEST).entity("Empty artifactName").build();
    }
    if (StringUtils.isEmpty(apiData.artifactType)) {
        if (StringUtils.isEmpty(apiData.artifactTemplateName)
                || StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
            if (StringUtils.isEmpty(apiData.artifactTemplate)) {
                return Response.status(Status.BAD_REQUEST)
                        .entity("No artifact type given and no template given. Cannot guess artifact type")
                        .build();
            }
        }
    }

    if (!StringUtils.isEmpty(apiData.autoGenerateIA)) {
        if (StringUtils.isEmpty(apiData.javaPackage)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("no java package name supplied for IA auto generation.").build();
        }
        if (StringUtils.isEmpty(apiData.interfaceName)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("no interface name supplied for IA auto generation.").build();
        }
    }

    // convert second calling form to first calling form
    if (!StringUtils.isEmpty(apiData.artifactTemplate)) {
        QName qname = QName.valueOf(apiData.artifactTemplate);
        apiData.artifactTemplateName = qname.getLocalPart();
        apiData.artifactTemplateNamespace = qname.getNamespaceURI();
    }

    Document doc = null;

    // check artifact specific content for validity
    // if invalid, abort and do not create anything
    if (!StringUtils.isEmpty(apiData.artifactSpecificContent)) {
        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            StringReader sr = new StringReader(apiData.artifactSpecificContent);
            is.setCharacterStream(sr);
            doc = db.parse(is);
        } catch (Exception e) {
            // FIXME: currently we allow a single element only. However, the content should be internally wrapped by an (arbitrary) XML element as the content will be nested in the artifact element, too
            GenericArtifactsResource.LOGGER.debug("Invalid content", e);
            return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
        }
    }

    // determine artifactTemplate and artifactType

    ArtifactTypeId artifactTypeId;
    ArtifactTemplateId artifactTemplateId = null;
    ArtifactTemplateResource artifactTemplateResource = null;

    boolean doAutoCreateArtifactTemplate = !(StringUtils.isEmpty(apiData.autoCreateArtifactTemplate)
            || apiData.autoCreateArtifactTemplate.equalsIgnoreCase("no")
            || apiData.autoCreateArtifactTemplate.equalsIgnoreCase("false"));
    if (!doAutoCreateArtifactTemplate) {
        // no auto creation
        if (!StringUtils.isEmpty(apiData.artifactTemplateName)
                && !StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
            QName artifactTemplateQName = new QName(apiData.artifactTemplateNamespace,
                    apiData.artifactTemplateName);
            artifactTemplateId = BackendUtils.getDefinitionsChildId(ArtifactTemplateId.class,
                    artifactTemplateQName);
        }
        if (StringUtils.isEmpty(apiData.artifactType)) {
            // derive the type from the artifact template
            if (artifactTemplateId == null) {
                return Response.status(Status.NOT_ACCEPTABLE).entity(
                        "No artifactTemplate and no artifactType provided. Deriving the artifactType is not possible.")
                        .build();
            }
            @NonNull
            final QName type = repository.getElement(artifactTemplateId).getType();
            artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, type);
        } else {
            // artifactTypeStr is directly given, use that
            artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, apiData.artifactType);
        }
    } else {
        // do the artifact template auto creation magic

        if (StringUtils.isEmpty(apiData.artifactType)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("Artifact template auto creation requested, but no artifact type supplied.")
                    .build();
        }

        artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, apiData.artifactType);
        // ensure that given type exists
        if (!repository.exists(artifactTypeId)) {
            LOGGER.debug("Artifact type {} is created", apiData.artifactType);
            final TArtifactType element = repository.getElement(artifactTypeId);
            try {
                repository.setElement(artifactTypeId, element);
            } catch (IOException e) {
                throw new WebApplicationException(e);
            }
        }

        if (StringUtils.isEmpty(apiData.artifactTemplateName)
                || StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
            // no explicit name provided
            // we use the artifactNameStr as prefix for the
            // artifact template name

            // we create a new artifact template in the namespace of the parent
            // element
            Namespace namespace = this.resWithNamespace.getNamespace();

            artifactTemplateId = new ArtifactTemplateId(namespace,
                    new XmlId(apiData.artifactName + "artifactTemplate", false));
        } else {
            QName artifactTemplateQName = new QName(apiData.artifactTemplateNamespace,
                    apiData.artifactTemplateName);
            artifactTemplateId = new ArtifactTemplateId(artifactTemplateQName);
        }

        // even if artifactTemplate does not exist, it is loaded
        final TArtifactTemplate artifactTemplate = repository.getElement(artifactTemplateId);
        artifactTemplate.setType(artifactTypeId.getQName());
        try {
            repository.setElement(artifactTemplateId, artifactTemplate);
        } catch (IOException e) {
            throw new WebApplicationException(e);
        }
    }

    // variable artifactTypeId is set
    // variable artifactTemplateId is not null if artifactTemplate has been generated

    // we have to generate the DA/IA resource now
    // Doing it here instead of doing it at the subclasses is dirty on the
    // one hand, but quicker to implement on the other hand

    // Create the artifact itself

    ArtifactT resultingArtifact;

    if (this instanceof ImplementationArtifactsResource) {
        ImplementationArtifact a = new ImplementationArtifact();
        // Winery internal id is the name of the artifact:
        // store the name
        a.setName(apiData.artifactName);
        a.setInterfaceName(apiData.interfaceName);
        a.setOperationName(apiData.operationName);
        assert (artifactTypeId != null);
        a.setArtifactType(artifactTypeId.getQName());
        if (artifactTemplateId != null) {
            a.setArtifactRef(artifactTemplateId.getQName());
        }
        if (doc != null) {
            // the content has been checked for validity at the beginning of the method.
            // If this point in the code is reached, the XML has been parsed into doc
            // just copy over the dom node. Hopefully, that works...
            a.getAny().add(doc.getDocumentElement());
        }

        this.list.add((ArtifactT) a);
        resultingArtifact = (ArtifactT) a;
    } else {
        // for comments see other branch

        TDeploymentArtifact a = new TDeploymentArtifact();
        a.setName(apiData.artifactName);
        assert (artifactTypeId != null);
        a.setArtifactType(artifactTypeId.getQName());
        if (artifactTemplateId != null) {
            a.setArtifactRef(artifactTemplateId.getQName());
        }
        if (doc != null) {
            a.getAny().add(doc.getDocumentElement());
        }

        this.list.add((ArtifactT) a);
        resultingArtifact = (ArtifactT) a;
    }

    // TODO: Check for error, and in case one found return it
    RestUtils.persist(super.res);

    if (StringUtils.isEmpty(apiData.autoGenerateIA)) {
        // No IA generation
        return Response.created(RestUtils.createURI(Util.URLencode(apiData.artifactName)))
                .entity(resultingArtifact).build();
    } else {
        // after everything was created, we fire up the artifact generation
        return this.generateImplementationArtifact(apiData.interfaceName, apiData.javaPackage, uriInfo,
                artifactTemplateId);
    }
}

From source file:org.ednovo.gooru.application.util.TaxonomyUtil.java

public static final void updateClassplanLibrary(String taxonomyPath, Integer rootCodeId) throws Exception {

    Document taxonomyXML = null;/*from w  w  w  .ja va 2 s .  com*/
    SAXReader reader = new SAXReader();
    try {
        taxonomyXML = reader.read(taxonomyPath + "/" + rootCodeId + ".xml");
    } catch (DocumentException e) {
        throw new MethodFailureException(e.getMessage());
    }

    String taxonomyStep2XML = XMLTransformer.getInstance().transform(taxonomyXML,
            "VIEW_CLASSPLAN_LIBRARY_XSL_PATH_STEP_1", taxonomyPath, null);

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(taxonomyStep2XML));
    taxonomyXML = reader.read(is);

    String taxonomyHTML = XMLTransformer.getInstance().transform(taxonomyXML,
            "VIEW_CLASSPLAN_LIBRARY_XSL_PATH_STEP_2", taxonomyPath, null);

    final String encoding = (new OutputStreamWriter(new ByteArrayOutputStream())).getEncoding();
    FileUtils.writeStringToFile(new File(taxonomyPath + "/taxonomy.html"), taxonomyHTML, encoding);
}

From source file:org.ednovo.gooru.application.util.TaxonomyUtil.java

public static final void updateTaxonomyTree(String taxonomyPath, Integer rootCodeId) throws Exception {
    Document taxonomyXML = null;/*from  w  w w . j av a 2s.  c  om*/
    SAXReader reader = new SAXReader();
    try {
        taxonomyXML = reader.read(taxonomyPath + "/" + rootCodeId + ".xml");
    } catch (DocumentException e) {
        throw new MethodFailureException(e.getMessage());
    }

    String taxonomyStep2XML = XMLTransformer.getInstance().transform(taxonomyXML,
            "VIEW_CLASSPLAN_LIBRARY_XSL_PATH_STEP_1", taxonomyPath, null);

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(taxonomyStep2XML));
    taxonomyXML = reader.read(is);

    String taxonomyStep4XML = XMLTransformer.getInstance().transform(taxonomyXML,
            "CLASSPLAN_LIBRARY_Tree_XSL_PATH_STEP_3", taxonomyPath, null);

    is.setCharacterStream(new StringReader(taxonomyStep4XML));
    taxonomyXML = reader.read(is);

    String taxonomyHTML = XMLTransformer.getInstance().transform(taxonomyXML,
            "CLASSPLAN_LIBRARY_Tree_XSL_PATH_STEP_4", taxonomyPath, null);

    final String encoding = (new OutputStreamWriter(new ByteArrayOutputStream())).getEncoding();
    FileUtils.writeStringToFile(new File(taxonomyPath + "/tree.html"), taxonomyHTML, encoding);
}

From source file:org.ednovo.gooru.application.util.TaxonomyUtil.java

public static final void updateResourceLibrary(String taxonomyPath, Integer rootCodeId) throws Exception {

    Document taxonomyXML = null;//from ww w.j  a v a2 s.  c  o m
    SAXReader reader = new SAXReader();
    try {
        taxonomyXML = reader.read(taxonomyPath + "/" + rootCodeId + ".xml");
    } catch (DocumentException e) {
        throw new MethodFailureException(e.getMessage());
    }
    String taxonomyStep2XML = XMLTransformer.getInstance().transform(taxonomyXML,
            "VIEW_CLASSPLAN_LIBRARY_XSL_PATH_STEP_1", taxonomyPath, null);

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(taxonomyStep2XML));
    taxonomyXML = reader.read(is);

    try {
        String taxonomyHTMLResource = XMLTransformer.getInstance().transform(taxonomyXML,
                "VIEW_RESOURCE_LIBRARY_XSL_PATH_STEP_2", taxonomyPath, null);
        final String encoding = (new OutputStreamWriter(new ByteArrayOutputStream())).getEncoding();
        FileUtils.writeStringToFile(new File(taxonomyPath + "/taxonomyResource.html"), taxonomyHTMLResource,
                encoding);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:org.exist.collections.Collection.java

private InputSource closeShieldInputSource(final InputSource source) {

    final InputSource protectedInputSource = new InputSource();
    protectedInputSource.setEncoding(source.getEncoding());
    protectedInputSource.setSystemId(source.getSystemId());
    protectedInputSource.setPublicId(source.getPublicId());

    if (source.getByteStream() != null) {
        //TODO consider AutoCloseInputStream
        final InputStream closeShieldByteStream = new CloseShieldInputStream(source.getByteStream());
        protectedInputSource.setByteStream(closeShieldByteStream);
    }//from www . j a  v  a 2  s.  c  o m

    if (source.getCharacterStream() != null) {
        //TODO consider AutoCloseReader
        final Reader closeShieldReader = new CloseShieldReader(source.getCharacterStream());
        protectedInputSource.setCharacterStream(closeShieldReader);
    }

    return protectedInputSource;
}

From source file:org.exist.collections.MutableCollection.java

private InputSource closeShieldInputSource(final InputSource source) {
    final InputSource protectedInputSource = new InputSource();
    protectedInputSource.setEncoding(source.getEncoding());
    protectedInputSource.setSystemId(source.getSystemId());
    protectedInputSource.setPublicId(source.getPublicId());

    if (source.getByteStream() != null) {
        //TODO consider AutoCloseInputStream
        final InputStream closeShieldByteStream = new CloseShieldInputStream(source.getByteStream());
        protectedInputSource.setByteStream(closeShieldByteStream);
    }/* www  .j  a va2  s .c  o  m*/

    if (source.getCharacterStream() != null) {
        //TODO consider AutoCloseReader
        final Reader closeShieldReader = new CloseShieldReader(source.getCharacterStream());
        protectedInputSource.setCharacterStream(closeShieldReader);
    }

    return protectedInputSource;
}

From source file:org.jboss.elasticsearch.river.remote.sitemap.SiteMapParser.java

/**
 * Parse the given XML content./*from w  w  w. j a  v  a2 s  .co m*/
 * 
 * @param sitemapUrl
 * @param xmlContent
 * @return
 * @throws UnknownFormatException
 */
private AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException {

    BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent));
    InputSource is = new InputSource();
    is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs)));
    return processXml(sitemapUrl, is);
}

From source file:org.kuali.kra.service.impl.ResearchAreasServiceBaseImpl.java

/**
 * The format is as follows:/*from ww  w .  j a  v a  2 s .c  o m*/
 * <pre>
 * {@code
 * <RaChanges>
 *   <RaChangesElement>
 *       <RaCreate>
 *           <Code></Code>
 *           <ParentCode></ParentCode>
 *           <Description></Description>
 *           <Active></Active>
 *       </RaCreate>
 *       <RaUpdateDescription>
 *           <Code></Code>
 *           <Description></Description>
 *       </RaUpdateDescription>
 *       <RaUpdateActiveIndicator>
 *           <Code></Code>
 *           <Active></Active>
 *       </RaUpdateActiveIndicator>
 *       <RaUpdateParent>
 *           <Code></Code>
 *           <OldParent></OldParent>
 *           <NewParent></NewParent>
 *       </RaUpdateParent>
 *       <RaDelete>
 *           <Code></Code>
 *       </RaDelete>
 *   </RaChangesElement>
 * </RaChanges>
 * }
 * </pre>
 * @throws SAXException 
 * @throws IOException 
 * @throws ParserConfigurationException 
 * 
 * @see org.kuali.kra.irb.service.ResearchAreasService#saveResearchAreas(java.lang.String)
 */
public void saveResearchAreas(String raChangeXML)
        throws ParserConfigurationException, IOException, SAXException {
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(raChangeXML));
    Document raChangesDocument;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    raChangesDocument = db.parse(is);
    List<Element> raChanges = getRaChanges(raChangesDocument);
    for (Element raChange : raChanges) {
        Map<String, Map<String, String>> details = getRaChangeDetails(raChange);
        if (details.containsKey(CREATE_RESEARCH_AREA)) {
            boolean active = StringUtils.equalsIgnoreCase(details.get(CREATE_RESEARCH_AREA).get(ACTIVE), TRUE)
                    ? true
                    : false;

            /*
            ResearchArea researchArea = new ResearchArea(details.get(CREATE_RESEARCH_AREA).get(CODE), details.get(CREATE_RESEARCH_AREA)
                .get(PARENT_CODE), details.get(CREATE_RESEARCH_AREA).get(DESCRIPTION), active);
                */

            ResearchAreaBase researchArea = getNewResearchAreaInstanceHook(
                    details.get(CREATE_RESEARCH_AREA).get(CODE),
                    details.get(CREATE_RESEARCH_AREA).get(PARENT_CODE),
                    details.get(CREATE_RESEARCH_AREA).get(DESCRIPTION), active);

            businessObjectService.save(researchArea);
            setHasChildrenFlag(details.get(CREATE_RESEARCH_AREA).get(PARENT_CODE), true);

        }
        if (details.containsKey(UPDATE_RESEARCH_AREA_DESCRIPTION)) {
            ResearchAreaBase researchArea = businessObjectService.findBySinglePrimaryKey(
                    getResearchAreaBOClassHook(), details.get(UPDATE_RESEARCH_AREA_DESCRIPTION).get(CODE));
            researchArea.setDescription(details.get(UPDATE_RESEARCH_AREA_DESCRIPTION).get(DESCRIPTION));
            businessObjectService.save(researchArea);
        }
        if (details.containsKey(UPDATE_RESEARCH_AREA_ACTIVE_FLAG)) {
            // with kcirb-1424's changes, the 'update' will now always be an activation (deactivations are carried out seperately).
            // boolean active = StringUtils.equalsIgnoreCase(details.get(UPDATE_RESEARCH_AREA_ACTIVE_FLAG).get(ACTIVE), TRUE) ? true : false;
            ResearchAreaBase researchArea = businessObjectService.findBySinglePrimaryKey(
                    getResearchAreaBOClassHook(), details.get(UPDATE_RESEARCH_AREA_ACTIVE_FLAG).get(CODE));
            researchArea.setActive(true);
            businessObjectService.save(researchArea);
            // inactivateChildrenResearchAreas(details.get(UPDATE_RESEARCH_AREA_ACTIVE_FLAG).get(CODE));
        }
        if (details.containsKey(UPDATE_PARENT_RESEARCH_AREA)) {
            ResearchAreaBase researchArea = businessObjectService.findBySinglePrimaryKey(
                    getResearchAreaBOClassHook(), details.get(UPDATE_PARENT_RESEARCH_AREA).get(CODE));
            researchArea.setParentResearchAreaCode(details.get(UPDATE_PARENT_RESEARCH_AREA).get(NEW_PARENT));
            businessObjectService.save(researchArea);
            setHasChildrenFlag(details.get(UPDATE_PARENT_RESEARCH_AREA).get(NEW_PARENT), true);
            updateHasChildrenFlag(details.get(UPDATE_PARENT_RESEARCH_AREA).get("OldParent"));
        }
    }
}

From source file:org.kuali.kra.service.impl.ResearchAreasServiceImpl.java

/**
 * The format is as follows:/*from ww  w  . j av a 2s  .  c  o  m*/
 * <pre>
 * {@code
 * <RaChanges>
 *   <RaChangesElement>
 *       <RaCreate>
 *           <Code></Code>
 *           <ParentCode></ParentCode>
 *           <Description></Description>
 *           <Active></Active>
 *       </RaCreate>
 *       <RaUpdateDescription>
 *           <Code></Code>
 *           <Description></Description>
 *       </RaUpdateDescription>
 *       <RaUpdateActiveIndicator>
 *           <Code></Code>
 *           <Active></Active>
 *       </RaUpdateActiveIndicator>
 *       <RaUpdateParent>
 *           <Code></Code>
 *           <OldParent></OldParent>
 *           <NewParent></NewParent>
 *       </RaUpdateParent>
 *       <RaDelete>
 *           <Code></Code>
 *       </RaDelete>
 *   </RaChangesElement>
 * </RaChanges>
 * }
 * </pre>
 * @throws SAXException 
 * @throws IOException 
 * @throws ParserConfigurationException 
 * 
 * @see org.kuali.kra.service.ResearchAreasService#saveResearchAreas(java.lang.String)
 */
public void saveResearchAreas(String raChangeXML)
        throws ParserConfigurationException, IOException, SAXException {
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(raChangeXML));
    Document raChangesDocument;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    raChangesDocument = db.parse(is);
    List<Element> raChanges = getRaChanges(raChangesDocument);
    for (Element raChange : raChanges) {
        Map<String, Map<String, String>> details = getRaChangeDetails(raChange);
        if (details.containsKey(CREATE_RESEARCH_AREA)) {
            boolean active = StringUtils.equalsIgnoreCase(details.get(CREATE_RESEARCH_AREA).get(ACTIVE), TRUE)
                    ? true
                    : false;
            ResearchArea researchArea = new ResearchArea(details.get(CREATE_RESEARCH_AREA).get(CODE),
                    details.get(CREATE_RESEARCH_AREA).get(PARENT_CODE),
                    details.get(CREATE_RESEARCH_AREA).get(DESCRIPTION), active);
            businessObjectService.save(researchArea);
            setHasChildrenFlag(details.get(CREATE_RESEARCH_AREA).get(PARENT_CODE), true);

        }
        if (details.containsKey(UPDATE_RESEARCH_AREA_DESCRIPTION)) {
            ResearchArea researchArea = businessObjectService.findBySinglePrimaryKey(ResearchArea.class,
                    details.get(UPDATE_RESEARCH_AREA_DESCRIPTION).get(CODE));
            researchArea.setDescription(details.get(UPDATE_RESEARCH_AREA_DESCRIPTION).get(DESCRIPTION));
            businessObjectService.save(researchArea);
        }
        if (details.containsKey(UPDATE_RESEARCH_AREA_ACTIVE_FLAG)) {
            // with kcirb-1424's changes, the 'update' will now always be an activation (deactivations are carried out seperately).
            // boolean active = StringUtils.equalsIgnoreCase(details.get(UPDATE_RESEARCH_AREA_ACTIVE_FLAG).get(ACTIVE), TRUE) ? true : false;
            ResearchArea researchArea = businessObjectService.findBySinglePrimaryKey(ResearchArea.class,
                    details.get(UPDATE_RESEARCH_AREA_ACTIVE_FLAG).get(CODE));
            researchArea.setActive(true);
            businessObjectService.save(researchArea);
            // inactivateChildrenResearchAreas(details.get(UPDATE_RESEARCH_AREA_ACTIVE_FLAG).get(CODE));
        }
        if (details.containsKey(UPDATE_PARENT_RESEARCH_AREA)) {
            ResearchArea researchArea = businessObjectService.findBySinglePrimaryKey(ResearchArea.class,
                    details.get(UPDATE_PARENT_RESEARCH_AREA).get(CODE));
            researchArea.setParentResearchAreaCode(details.get(UPDATE_PARENT_RESEARCH_AREA).get(NEW_PARENT));
            businessObjectService.save(researchArea);
            setHasChildrenFlag(details.get(UPDATE_PARENT_RESEARCH_AREA).get(NEW_PARENT), true);
            updateHasChildrenFlag(details.get(UPDATE_PARENT_RESEARCH_AREA).get("OldParent"));
        }
    }
}