Example usage for org.w3c.dom Document appendChild

List of usage examples for org.w3c.dom Document appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Document appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * Returns a new created instance document.
 * <p/>/*w w w  . j a  va  2s. c o m*/
 * If this instance has an original instance, it will be imported into this
 * new document. Otherwise the new document is left empty.
 *
 * @return a new created instance document.
 * @throws de.betterform.xml.xforms.exception.XFormsException
 */
private Document createInstanceDocument() throws XFormsException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().newDocument();

        if (this.initialInstance != null) {
            Node imported = document.importNode(this.initialInstance.cloneNode(true), true);
            document.appendChild(imported);

            if (getXFormsAttribute(SRC_ATTRIBUTE) == null && getXFormsAttribute(RESOURCE_ATTRIBUTE) == null) {
                NamespaceResolver.applyNamespaces(this.element, document.getDocumentElement());
            }
        }

        return document;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Transform into formatted XML./*from   w  ww . j a  va  2  s  . co m*/
 */
private String getFormattedXml(Node node) {
    Document document = node.getOwnerDocument().getImplementation().createDocument("", "fake", null);
    Element copy = (Element) document.importNode(node, true);
    document.importNode(node, false);
    document.removeChild(document.getDocumentElement());
    document.appendChild(copy);
    DOMImplementation domImpl = document.getImplementation();
    DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
    LSSerializer serializer = domImplLs.createLSSerializer();
    serializer.getDomConfig().setParameter("format-pretty-print", true);
    return serializer.writeToString(document);
}

From source file:org.callimachusproject.xproc.Pipeline.java

private XdmNode parse(String systemId, InputStream source, String media, XProcConfiguration config)
        throws IOException, SAXException, ParserConfigurationException {
    if (source == null && media == null)
        return null;
    try {//from w  ww .  j av  a2s. c  o m
        FluidType type = new FluidType(InputStream.class, media);
        if (type.isXML())
            return resolver.parse(systemId, source);
        Document doc = DocumentFactory.newInstance().newDocument();
        if (systemId != null) {
            doc.setDocumentURI(systemId);
        }
        Element data = doc.createElementNS(XPROC_STEP, DATA);
        data.setAttribute("content-type", media);
        if (type.isText()) {
            Charset charset = type.getCharset();
            if (charset == null) {
                charset = Charset.forName("UTF-8");
            }
            if (source != null) {
                appendText(new InputStreamReader(source, charset), doc, data);
            }
        } else if (source != null) {
            data.setAttribute("encoding", "base64");
            appendBase64(source, doc, data);
        }

        doc.appendChild(data);
        return config.getProcessor().newDocumentBuilder().wrap(doc);
    } finally {
        if (source != null) {
            source.close();
        }
    }
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void mkdir(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws RemoteException, IndelibleWebAccessException {
    Element rootElem = buildDoc.createElement("mkdir");
    buildDoc.appendChild(rootElem);
    String path = req.getPathInfo();
    FilePath reqPath = FilePath.getFilePath(path);
    if (reqPath == null || reqPath.getNumComponents() < 2)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

    // Should be an absolute path
    reqPath = reqPath.removeLeadingComponent();
    String fsIDStr = reqPath.getComponent(0);
    IndelibleFSVolumeIF volume = getVolume(fsIDStr);
    if (volume == null)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError, null);
    FilePath mkdirPath = reqPath.removeLeadingComponent();
    try {//from   www . j a v  a2 s .  c o m
        FilePath parentPath = mkdirPath.getParent();
        FilePath childPath = mkdirPath.getPathRelativeTo(parentPath);
        if (childPath.getNumComponents() != 1)
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
        IndelibleFileNodeIF parentNode = (IndelibleFileNodeIF) volume
                .getObjectByPath(parentPath.makeAbsolute());
        if (!parentNode.isDirectory())
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
        IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode;
        connection.startTransaction();
        CreateDirectoryInfo createInfo = parentDirectory.createChildDirectory(childPath.getName());
        connection.commit();
        XMLUtils.appendSingleValElement(buildDoc, rootElem, "fileID",
                createInfo.getCreatedNode().getObjectID().toString());
    } catch (ObjectNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
    } catch (PermissionDeniedException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
    } catch (IOException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
    } catch (FileExistsException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kDestinationExists, e);
    }
}

From source file:com.microsoft.windowsazure.management.sql.ServerOperationsImpl.java

/**
* Provisions a new SQL Database server in a subscription.
*
* @param parameters Required. The parameters needed to provision a server.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body./*from   w  w w  .  j  av  a2 s. com*/
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response returned from the Create Server operation.  This
* contains all the information returned from the service when a server is
* created.
*/
@Override
public ServerCreateResponse create(ServerCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getAdministratorPassword() == null) {
        throw new NullPointerException("parameters.AdministratorPassword");
    }
    if (parameters.getAdministratorUserName() == null) {
        throw new NullPointerException("parameters.AdministratorUserName");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element serverElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
            "Server");
    requestDoc.appendChild(serverElement);

    Element administratorLoginElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLogin");
    administratorLoginElement.appendChild(requestDoc.createTextNode(parameters.getAdministratorUserName()));
    serverElement.appendChild(administratorLoginElement);

    Element administratorLoginPasswordElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword");
    administratorLoginPasswordElement
            .appendChild(requestDoc.createTextNode(parameters.getAdministratorPassword()));
    serverElement.appendChild(administratorLoginPasswordElement);

    Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
            "Location");
    locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
    serverElement.appendChild(locationElement);

    if (parameters.getVersion() != null) {
        Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
                "Version");
        versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion()));
        serverElement.appendChild(versionElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_CREATED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ServerCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServerCreateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element serverNameElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/sqlazure/2010/12/", "ServerName");
            if (serverNameElement != null) {
                Attr fullyQualifiedDomainNameAttribute = serverNameElement.getAttributeNodeNS(
                        "http://schemas.microsoft.com/sqlazure/2010/12/", "FullyQualifiedDomainName");
                if (fullyQualifiedDomainNameAttribute != null) {
                    result.setFullyQualifiedDomainName(fullyQualifiedDomainNameAttribute.getValue());
                }

                result.setServerName(serverNameElement.getTextContent());
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:no.dusken.barweb.view.XListView.java

private Document generateXml(List<BarPerson> barPersons, Gjeng gjeng, List<Vare> varer, int lowlimit,
        Boolean panger) {//from   ww  w . ja  va  2s.c  o  m
    Document dom = null;
    //get an instance of factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        //get an instance of builder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //create an instance of DOM
        dom = db.newDocument();

    } catch (ParserConfigurationException pce) {
        log.error("Error when generating x-list");
    }
    Element root = dom.createElement("xlist");
    root.setAttribute("gjeng", gjeng.getName());
    SimpleDateFormat dateformat = new SimpleDateFormat("d. MMMMMMMMM yyyy - HH:mm", new Locale("no"));
    root.setAttribute("generated", dateformat.format((new GregorianCalendar()).getTime()));
    root.setAttribute("magicNumber", String.valueOf(((new Random()).nextDouble() * 1000)));
    root.setAttribute("panger", panger.toString());
    dom.appendChild(root);
    Element personsEle = dom.createElement("barPersons");

    for (BarPerson p : barPersons) {
        Element personEle = createPersonElement(p, dom, lowlimit);
        personsEle.appendChild(personEle);
    }

    root.appendChild(personsEle);

    Element vareEle = dom.createElement("varer");

    for (Vare v : varer) {
        Element vare = createVareElement(v, dom);
        vareEle.appendChild(vare);
    }
    root.appendChild(vareEle);

    return dom;
}

From source file:com.microsoft.windowsazure.management.sql.ServerOperationsImpl.java

/**
* Changes the administrative password of an existing Azure SQL Database
* Server for a given subscription.//from w w  w . jav  a2s. co m
*
* @param serverName Required. The name of the Azure SQL Database Server
* that will have the administrator password changed.
* @param parameters Required. The necessary parameters for modifying the
* adminstrator password for a server.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse changeAdministratorPassword(String serverName,
        ServerChangeAdministratorPasswordParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getNewPassword() == null) {
        throw new NullPointerException("parameters.NewPassword");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "changeAdministratorPasswordAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("op=ResetPassword");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element administratorLoginPasswordElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword");
    requestDoc.appendChild(administratorLoginPasswordElement);

    administratorLoginPasswordElement.appendChild(requestDoc.createTextNode(parameters.getNewPassword()));

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:es.upm.fi.dia.oeg.sitemap4rdf.Generator.java

/**
 * Generates the sitemap.xml file//from  w w w. ja v a2 s . c  o m
 * @param result an existing ResultSet if we did cross the limit of URLs per sitemap.xml file
 * @param index of the current generation of the sitemap file, useful when we are creating sitemap_index.xml files 
 */
protected void generateSiteMap(ResultSet result, int index) {
    try {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement(urlSetTag);
        root.setAttribute(XMLNS, namespace);

        if (!semanticSectionGenerated) {
            root.setAttribute(XMLNS + ":" + PREFIX_SEMANTIC_SITEMAP, NS_SEMANTIC_SITEMAP);
        }

        doc.appendChild(root);
        generateSemanticSection(doc, root);

        ResultSet rs = generateFromEndPoint(doc, root, result);
        doc.setXmlStandalone(true);

        String outputFileName = (index == 0) ? (outputFile + extensionOutputFile)
                : (outputFile + index + extensionOutputFile);
        //String outputFileNameDirIncluded = outputFileName;
        //if (outputDir!=null && !outputDir.isEmpty())
        //outputFileNameDirIncluded = outputDir+outputFileName;

        if (files == null)
            files = new HashMap<String, Document>();

        files.put(outputFileName, doc);

        if (rs != null)
            generateSiteMap(rs, ++index);

    } catch (ParserConfigurationException e) {
        logger.debug("ParserConfigurationException ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    }
}

From source file:com.photon.phresco.framework.rest.api.ParameterService.java

private static boolean saveCofiguration(String appDirName, String module, Publication config)
        throws PhrescoException {
    boolean fileSaved = false;
    try {/*from   w w w. j  a v a2 s  .  c o m*/
        String rootModulePath = "";
        String subModuleName = "";
        if (StringUtils.isNotEmpty(module)) {
            rootModulePath = Utility.getProjectHome() + appDirName;
            subModuleName = module;
        } else {
            rootModulePath = Utility.getProjectHome() + appDirName;
        }
        String appDirPath = Utility.getProjectHome() + appDirName;
        String dotPhrescoFolderPath = Utility.getDotPhrescoFolderPath(appDirPath, subModuleName);

        String publicationConfigPath = dotPhrescoFolderPath + File.separator + PUBLICATION_CONFIG_FILE;

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = docFactory.newDocumentBuilder();
        Document doc = documentBuilder.newDocument();

        Element rootElement = doc.createElement(PUBLICATIONS);
        doc.appendChild(rootElement);

        Element publication = doc.createElement(PUBLICATION);
        publication.setAttribute(PUBLICATION_NAME, config.getPublicationName());
        publication.setAttribute(PUBLICATION_TYPE, config.getPublicationType());
        rootElement.appendChild(publication);

        Element publicationPath = doc.createElement(PUBLICATION_PATH);
        publicationPath.setTextContent(config.getPublicationPath());
        rootElement.appendChild(publicationPath);

        Element publicationUrl = doc.createElement(PUBLICATION_URL);
        publicationUrl.setTextContent(config.getPublicationUrl());
        rootElement.appendChild(publicationUrl);

        Element imageUrl = doc.createElement(IMAGE_URL);
        imageUrl.setTextContent(config.getImageUrl());
        rootElement.appendChild(imageUrl);

        Element imagePath = doc.createElement(IMAGE_PATH);
        imagePath.setTextContent(config.getImagePath());
        rootElement.appendChild(imagePath);

        Element environment = doc.createElement(ENVIRONMENT);
        environment.setTextContent(config.getEnvironment());
        rootElement.appendChild(environment);

        Element publicationKey = doc.createElement(PUBLICATION_KEY);
        publicationKey.setTextContent(config.getPublicationKey());
        rootElement.appendChild(publicationKey);

        Element parentPublications = doc.createElement(PARENT_PUBLICATIONS);
        List<Map<String, String>> subPublications = config.getParentPublications();
        if (CollectionUtils.isNotEmpty(subPublications)) {
            for (Map<String, String> map : subPublications) {
                Element parentPublication = doc.createElement(PARENT_SUB_PUBLICATION);
                Set<String> keySet = map.keySet();
                if (CollectionUtils.isNotEmpty(keySet)) {
                    for (String keys : keySet) {
                        if (keys.equalsIgnoreCase(PARENT_NAME)) {
                            parentPublication.setAttribute(PARENT_NAME, map.get(keys));
                            parentPublications.appendChild(parentPublication);
                        } else if (keys.equalsIgnoreCase(PRIORITY)) {
                            parentPublication.setAttribute(PRIORITY, map.get(keys));
                            parentPublications.appendChild(parentPublication);
                        }
                    }
                }
            }
        }

        rootElement.appendChild(parentPublications);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, YES);

        Pattern p = Pattern.compile("%20");
        p.matcher(publicationConfigPath);
        File path = new File(publicationConfigPath);

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(path.toString());

        transformer.transform(source, result);
        fileSaved = true;

    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (TransformerConfigurationException e) {
        throw new PhrescoException(e);
    } catch (TransformerException e) {
        throw new PhrescoException(e);
    } catch (PhrescoException e) {
        throw new PhrescoException(e);
    }
    return fileSaved;
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void allocate(HttpServletRequest req, HttpServletResponse resp, String lengthString, Document buildDoc)
        throws RemoteException, IndelibleWebAccessException {
    Element rootElem = buildDoc.createElement("allocate");
    buildDoc.appendChild(rootElem);
    String path = req.getPathInfo();
    FilePath reqPath = FilePath.getFilePath(path);
    if (reqPath == null || reqPath.getNumComponents() < 2)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
    long allocateLength;
    try {/*from   w  w w  .java2s .c o m*/
        allocateLength = Long.parseLong(lengthString);
    } catch (NumberFormatException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, e);
    }
    // Should be an absolute path
    reqPath = reqPath.removeLeadingComponent();
    String fsIDStr = reqPath.getComponent(0);
    IndelibleFSVolumeIF volume = getVolume(fsIDStr);
    if (volume == null)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError, null);
    FilePath allocatePath = reqPath.removeLeadingComponent();
    try {
        FilePath parentPath = allocatePath.getParent();
        FilePath childPath = allocatePath.getPathRelativeTo(parentPath);
        if (childPath.getNumComponents() != 1)
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
        IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute());
        if (!parentNode.isDirectory())
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
        IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode;
        connection.startTransaction();
        IndelibleFileNodeIF childNode = null;
        childNode = parentDirectory.getChildNode(childPath.getName());
        if (childNode == null) {
            CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true);
            childNode = childInfo.getCreatedNode();
            IndelibleFSForkIF dataFork = childNode.getFork("data", true);
            dataFork.extend(allocateLength);
            XMLUtils.appendSingleValElement(buildDoc, rootElem, "fileID",
                    childInfo.getCreatedNode().getObjectID().toString());
            XMLUtils.appendSingleValElement(buildDoc, rootElem, "length", Long.toString(allocateLength));
        } else {
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kDestinationExists, null);
        }
        if (childNode.isDirectory())
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null);

        connection.commit();

    } catch (ObjectNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
    } catch (PermissionDeniedException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
    } catch (IOException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
    } catch (FileExistsException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kDestinationExists, e);
    } catch (ForkNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
    }
}