Example usage for javax.xml.xpath XPathConstants STRING

List of usage examples for javax.xml.xpath XPathConstants STRING

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants STRING.

Prototype

QName STRING

To view the source code for javax.xml.xpath XPathConstants STRING.

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:org.ala.harvester.FlickrHarvester.java

private boolean isDocExtractionSuccessful(org.w3c.dom.Document resDom) throws Exception {

    if (resDom == null) {
        return false;
    }//from ww w . ja v  a 2s  . c o m

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    // <rsp stat="fail">
    // <err code="[error-code]" msg="[error-message]" />
    // </rsp>

    String xPathToStatus = "/rsp/@stat";

    String statusString = null;
    try {
        statusString = (String) xpath.evaluate(xPathToStatus, resDom, XPathConstants.STRING);
    } catch (XPathExpressionException getStatusStringErr) {
        String errMsg = "Failed to obtain Flickr REST response's status string.";
        logger.error(errMsg);
        throw new Exception(errMsg, getStatusStringErr);
    }
    logger.debug("Response status: " + statusString);
    if ("ok".equals(statusString)) {
        return true;
    } else {
        logger.error("Error response status: " + statusString);
    }

    // Status is false.
    String flickrErrCode = null;
    String flickrErrMsg = null;
    try {
        flickrErrCode = (String) xpath.evaluate("/rsp/err/@code", resDom, XPathConstants.STRING);
        flickrErrMsg = (String) xpath.evaluate("/rsp/err/@msg", resDom, XPathConstants.STRING);
    } catch (XPathExpressionException getErrDetailsErr) {
        String errMsg = "Failed to obtain Flickr REST response's error code and message.";
        logger.error(errMsg);
        throw new Exception(errMsg, getErrDetailsErr);
    }

    String errMsg = "Flickr REST response returned error.  Code: " + flickrErrCode + " " + "Message: " + "`"
            + flickrErrMsg + "`" + "\n";
    logger.error(errMsg);

    return false;
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument getStats(String collectionId)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;/*from   w  w w.  j  a va2 s. c o m*/
    String fq = !collectionId.isEmpty() ? "fq=parentIdentifier%3D" + collectionId + "&" : "";
    String urlStr = this.solrHost + "/select?q=*%3A*&" + fq + "wt=xml&stats=true&"
            + "stats.field=beginPosition&" + "stats.field=endPosition&" + "stats.field=orbitNumber&"
            + "stats.field=acquisitionStation&" + "facet.field=productType&" + "facet.field=platformShortName&"
            + "facet.field=platformSerialIdentifier&" + "facet.field=instrument&" + "facet.field=sensorType&"
            + "facet.field=compositeType&" + "facet.field=processingLevel&" + "facet.field=orbitType&"
            + "stats.field=resolution&" + "facet.field=spectralRange&" + "stats.field=wavelengths&"
            + "facet.field=useLimitation&" + "facet.field=hasSecurityConstraints&"
            + "facet.field=organisationName&" + "facet.field=dissemination&" + "facet.field=parentIdentifier&"
            + "facet.field=productionStatus&" + "facet.field=acquisitionType&" + "stats.field=orbitNumber&"
            + "facet.field=orbitDirection&" + "stats.field=track&" + "stats.field=frame&"
            + "facet.field=swathIdentifier&" + "stats.field=cloudCover&" + "stats.field=snowCover&"
            + "facet.field=productQualityDegradation&" + "facet.field=productQualityDegradationTag&"
            + "facet.field=processorName&" + "facet.field=processingCenter&" + "stats.field=processingDate&"
            + "facet.field=sensorMode&" + "facet.field=archivingCenter&" + "facet.field=processingMode&"
            + "facet.field=acquisitionStation&" + "facet.field=acquisitionSubType&"
            + "stats.field=startTimeFromAscendingNode&" + "stats.field=completionTimeFromAscendingNode&"
            + "stats.field=illuminationAzimuthAngle&" + "stats.field=illuminationZenithAngle&"
            + "stats.field=illuminationElevationAngle&" + "facet.field=polarisationMode&"
            + "facet.field=polarisationChannels&" + "facet.field=antennaLookDirection&"
            + "stats.field=minimumIncidenceAngle&" + "stats.field=maximumIncidenceAngle&"
            + "stats.field=dopplerFrequency&" + "stats.field=incidenceAngleVariation&"
            + "rows=0&indent=true&facet=on&facet.mincount=1";

    Log.debug("The following search is goint to be executed:" + urlStr);
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        Log.error(solrResponse.getXMLDocumentString());
        throw new Exception(errorMessage);
    }

    return solrResponse;
}

From source file:com.fluidops.iwb.provider.XMLProvider.java

/**
 * Resolves a parametrized expression against a given context node.
 * A parametrized expression is a string of the form
 * //from  w  w  w  .j  a  va 2s  .c  om
 *   "Bla bla {XP1} some text {XP2} ... {XPn}",
 * 
 * where XP1 ... XPn are XPath expressions. When evaluating a parametrized
 * expression, the XPath expressions are evaluated against the context 
 * node and their occurences are replaced by the result nodes. The result
 * nodes is a list of strings, representing all permutations of solutions.
 * 
 * As an example, assume the parametrized expression is
 * 
 *   "{./name} - {./friend}"
 *  
 * and [[./name]] = { Pete }, [[./friend]] = { Jane, Joe }, then the result
 * of evaluating the parametrized expression is the list { "Pete - Jane", "Pete - Joe" }.
 * 
 * @param parametrizedExpression
 * @param context
 * @return
 */
protected List<String> resolveParametrizedExpression(String parametrizedExpression, Node context,
        boolean useNodeName, String ignoreIfMatches) {
    Map<String, XPathExpression> map = new HashMap<String, XPathExpression>();

    List<String> result = new ArrayList<String>();
    if (parametrizedExpression == null)
        return result;

    // first collect XPath Expression hidden in ruleExpression
    Map<String, List<String>> xPathExpressions = new HashMap<String, List<String>>();
    Matcher m = PARAMETRIZED_EXPRESSION_PATTERN.matcher(parametrizedExpression);
    while (m.find())
        xPathExpressions.put(m.group(0), new ArrayList<String>());

    XPath xpathDPExp = xpf.newXPath();
    xpathDPExp.setNamespaceContext(ctx);
    for (Entry<String, List<String>> entry : xPathExpressions.entrySet()) {
        String xPathExpression = entry.getKey();
        try {
            XPathExpression xpathExp = map.get(xPathExpression);
            if (xpathExp == null) {
                xpathExp = xpathDPExp.compile(xPathExpression.substring(1, xPathExpression.length() - 1));
                map.put(xPathExpression, xpathExp);
            }

            try {
                NodeList dpNodeList = (NodeList) xpathExp.evaluate(context, XPathConstants.NODESET);

                for (int i = 0; i < dpNodeList.getLength(); i++) {
                    Node dpNode = dpNodeList.item(i);
                    String dpNodeVal = null;
                    if (useNodeName)
                        dpNodeVal = dpNode.getNodeName();
                    else {
                        if (dpNode instanceof Element)
                            dpNodeVal = dpNode.getTextContent();
                        else
                            dpNodeVal = dpNode.getNodeValue();
                    }
                    if (!StringUtil.isNullOrEmpty(dpNodeVal))
                        entry.getValue().add(dpNodeVal);
                }
            } catch (XPathExpressionException isString) {
                String string = (String) xpathExp.evaluate(context, XPathConstants.STRING);
                if (!StringUtil.isNullOrEmpty(string))
                    entry.getValue().add(string);
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return result; // error
        }
    }

    // and compute set of all Literals
    result.add(parametrizedExpression);
    for (Entry<String, List<String>> entry : xPathExpressions.entrySet()) {
        String outerKey = entry.getKey();
        List<String> tempResult = new ArrayList<String>();
        List<String> outer = entry.getValue();
        for (int i = 0; i < outer.size(); i++) {
            for (String res : result) {
                while (res.contains(outerKey))
                    res = res.replace(outerKey, outer.get(i));
                tempResult.add(res);
            }
        }
        result = tempResult;
    }

    if (StringUtil.isNullOrEmpty(ignoreIfMatches))
        return result;

    // else: we filter the result
    List<String> resultFiltered = new ArrayList<String>();
    for (String s : result) {
        if (!s.matches(ignoreIfMatches))
            resultFiltered.add(s);
    }
    return resultFiltered;
}

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

/**
 * @param pluginXmlDTO//w  w  w  . j ava 2s .com
 * @param xpath
 * @param pluginPropertyNode
 * @throws
 */
private void extractPluginConfigs(PluginXmlDTO pluginXmlDTO, XPath xpath, NodeList pluginNodeList)
        throws UIException {
    try {
        NodeList pluginPropertyNode = (NodeList) xpath.evaluate(
                SystemConfigSharedConstants.PLUGIN_PROPERTY_EXPR, pluginNodeList.item(0),
                XPathConstants.NODESET);
        LOGGER.info("Extracting plugin Configs from the xml");
        List<PluginConfigXmlDTO> pluginConfigXmlDTOs = new ArrayList<PluginConfigXmlDTO>(0);
        int numberOfPluginConfigs = pluginPropertyNode.getLength();

        LOGGER.info(numberOfPluginConfigs + " plugin configs found: ");
        for (int index = 0; index < numberOfPluginConfigs; index++) {
            LOGGER.info("Plugin config " + index + ": ");
            boolean isMandetory;
            boolean isMultiValue;
            String configName = SystemConfigSharedConstants.EMPTY_STRING;
            String propertyType = SystemConfigSharedConstants.EMPTY_STRING;
            String propertyDescription = SystemConfigSharedConstants.EMPTY_STRING;
            String operation = SystemConfigSharedConstants.EMPTY_STRING;

            isMandetory = Boolean.parseBoolean(
                    (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_PROPERTY_IS_MANDETORY_EXPR,
                            pluginPropertyNode.item(index), XPathConstants.STRING));
            isMultiValue = Boolean.parseBoolean(
                    (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_PROPERTY_IS_MULTI_VALUES_EXPR,
                            pluginPropertyNode.item(index), XPathConstants.STRING));
            configName = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_PROPERTY_NAME_EXPR,
                    pluginPropertyNode.item(index), XPathConstants.STRING);
            propertyType = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_PROPERTY_TYPE_EXPR,
                    pluginPropertyNode.item(index), XPathConstants.STRING);
            propertyDescription = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_PROPERTY_DESC_EXPR,
                    pluginPropertyNode.item(index), XPathConstants.STRING);
            operation = (String) xpath.evaluate(SystemConfigSharedConstants.OPERATION,
                    pluginPropertyNode.item(index), XPathConstants.STRING);

            LOGGER.info("Extracting values for config: " + index);
            LOGGER.info("Is Mandatory" + isMandetory);
            LOGGER.info("Is Multivalue" + isMultiValue);
            LOGGER.info("Config Name" + configName);
            LOGGER.info("Property Type" + propertyType);
            LOGGER.info("Property Description" + propertyDescription);
            if (!configName.isEmpty() && !propertyType.isEmpty() && !propertyDescription.isEmpty()) {
                PluginConfigXmlDTO pluginConfigXmlDTO = new PluginConfigXmlDTO();
                pluginConfigXmlDTO.setPluginPropertyIsMandatory(isMandetory);
                pluginConfigXmlDTO.setPluginPropertyIsMultiValues(isMultiValue);
                pluginConfigXmlDTO.setPluginPropertyName(configName);
                pluginConfigXmlDTO.setPluginPropertyType(propertyType);
                pluginConfigXmlDTO.setPluginPropertyDesc(propertyDescription);
                pluginConfigXmlDTO.setOperation(operation);
                NodeList sampleValuesNode = (NodeList) xpath.evaluate(
                        SystemConfigSharedConstants.PLUGIN_PROPERTY_SAMPLE_VALUES_EXPR,
                        pluginPropertyNode.item(index), XPathConstants.NODESET);
                List<String> sampleValuesList = new ArrayList<String>(0);
                LOGGER.info("Extracting sample values: ");
                int numberOfSampleValues = sampleValuesNode.getLength();

                LOGGER.info(numberOfSampleValues + " sample values found");
                for (int sampleValueIndex = 0; sampleValueIndex < numberOfSampleValues; sampleValueIndex++) {

                    String sampleValue = (String) xpath.evaluate(
                            SystemConfigSharedConstants.PLUGIN_PROPERTY_SAMPLE_VALUE_EXPR,
                            sampleValuesNode.item(sampleValueIndex), XPathConstants.STRING);
                    LOGGER.info("Sample value " + sampleValueIndex + " :" + sampleValue);
                    sampleValuesList.add(sampleValue);
                }
                pluginConfigXmlDTO.setPluginPropertySampleValues(sampleValuesList);
                pluginConfigXmlDTOs.add(pluginConfigXmlDTO);
            } else {
                String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE;
                LOGGER.error(errorMsg);
                throw new UIException(errorMsg);
            }
        }
        pluginXmlDTO.setConfigXmlDTOs(pluginConfigXmlDTOs);
    } catch (XPathExpressionException e) {
        String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE;
        LOGGER.error(errorMsg, e);
        throw new UIException(errorMsg);
    }
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

private String evaluate(Document responseDoc, String expression) {
    Object result = evaluate(responseDoc, expression, XPathConstants.STRING);
    if (result == null || !(result instanceof String))
        return new String();
    return (String) result;
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Copy file that will displayed in Jmol
 * @param doc XML document/*from ww w .  j ava  2  s  .  c o m*/
 * @param rootElt Root element
 * @param xreader XPath reader for the document
 * @param dataDirPath Path to directory that contains analysis data
 * @param dirPath Path to experiment directory
 * @return XML element for Jmol data
 * @throws IOException 
 */
private Element pullJmolFile(Document doc, Node rootElt, XPathReader xreader, String dataDirPath,
        String dirPath) throws IOException {
    Element jmolElt = doc.createElement("jmol");

    String mainStructureRelPath = (String) xreader
            .read("ibiomes/directory/AVUs/AVU[@id='MAIN_3D_STRUCTURE_FILE']", XPathConstants.STRING);
    if (mainStructureRelPath != null && mainStructureRelPath.length() > 0) {
        String dataFileNewName = mainStructureRelPath.replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_");
        String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName;
        Files.copy(Paths.get(dirPath + PATH_FOLDER_SEPARATOR + mainStructureRelPath),
                Paths.get(dataFileDestPath), StandardCopyOption.REPLACE_EXISTING);
        //set read permissions
        if (!Utils.isWindows()) {
            Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.OWNER_WRITE);
            permissions.add(PosixFilePermission.OWNER_EXECUTE);
            permissions.add(PosixFilePermission.GROUP_READ);
            permissions.add(PosixFilePermission.OTHERS_READ);
            Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions);
        }
        jmolElt.setAttribute("path", dataFileNewName);
        jmolElt.setAttribute("name", mainStructureRelPath);

        NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dirPath + PATH_FOLDER_SEPARATOR
                + mainStructureRelPath + "']/AVUs/AVU", XPathConstants.NODESET);
        MetadataAVUList avuList = parseMetadata(avuNodes);
        String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION);
        if (description != null && description.length() > 0)
            jmolElt.setAttribute("description", description);
        rootElt.appendChild(jmolElt);

        return jmolElt;
    } else
        return null;
}

From source file:com.microsoftopentechnologies.intellij.helpers.azure.AzureRestAPIManager.java

@Override
public void createService(UUID subscriptionId, String region, String username, String password,
        String serviceName, String server, String database) throws AzureCmdException {
    try {//from ww  w  .ja v  a2  s.c o  m
        String path = String.format("/%s/applications", subscriptionId.toString());

        String JSONParameter;

        if (database == null || server == null) {
            String zumoServerId = UUID.randomUUID().toString().replace("-", "");
            String zumoDBId = UUID.randomUUID().toString().replace("-", "");
            String dbName = serviceName + "_db";

            JSONParameter = "{'SchemaVersion':'2012-05.1.0','Location':'" + region
                    + "','ExternalResources':{},'InternalResources':{'ZumoMobileService':"
                    + "{'ProvisioningParameters':{'Name':'" + serviceName + "','Location':'" + region
                    + "'},'ProvisioningConfigParameters':{'Server':{'StringConcat':"
                    + "[{'ResourceReference':'ZumoSqlServer_" + zumoServerId
                    + ".Name'},'.database.windows.net']},'Database':{'ResourceReference':'ZumoSqlDatabase_"
                    + zumoDBId + ".Name'},'AdministratorLogin':'" + username
                    + "','AdministratorLoginPassword':'" + password + "'},'Version':'2012-05-21.1.0',"
                    + "'Name':'ZumoMobileService','Type':'Microsoft.WindowsAzure.MobileServices.MobileService'},'ZumoSqlServer_"
                    + zumoServerId + "':{'ProvisioningParameters':{'AdministratorLogin':'" + username
                    + "','AdministratorLoginPassword':'" + password + "','Location':'" + region
                    + "'},'ProvisioningConfigParameters':{'FirewallRules':[{'Name':'AllowAllWindowsAzureIps','StartIPAddress':'0.0.0.0','EndIPAddress':'0.0.0.0'}]},"
                    + "'Version':'1.0','Name':'ZumoSqlServer_" + zumoServerId
                    + "','Type':'Microsoft.WindowsAzure.SQLAzure.Server'},'ZumoSqlDatabase_" + zumoDBId
                    + "':{'ProvisioningParameters':{'Name':'" + dbName
                    + "','Edition':'WEB','MaxSizeInGB':'1','DBServer':{'ResourceReference':'ZumoSqlServer_"
                    + zumoServerId
                    + ".Name'},'CollationName':'SQL_Latin1_General_CP1_CI_AS'},'Version':'1.0','Name':'ZumoSqlDatabase_"
                    + zumoDBId + "','Type':'Microsoft.WindowsAzure.SQLAzure.DataBase'}}}";
        } else {
            String zumoServerId = UUID.randomUUID().toString().replace("-", "");
            String zumoDBId = UUID.randomUUID().toString().replace("-", "");

            JSONParameter = "{'SchemaVersion':'2012-05.1.0','Location':'West US','ExternalResources':{'ZumoSqlServer_"
                    + zumoServerId + "':{'Name':'ZumoSqlServer_" + zumoServerId + "',"
                    + "'Type':'Microsoft.WindowsAzure.SQLAzure.Server','URI':'https://management.core.windows.net:8443/"
                    + subscriptionId.toString() + "/services/sqlservers/servers/" + server + "'},"
                    + "'ZumoSqlDatabase_" + zumoDBId + "':{'Name':'ZumoSqlDatabase_" + zumoDBId
                    + "','Type':'Microsoft.WindowsAzure.SQLAzure.DataBase',"
                    + "'URI':'https://management.core.windows.net:8443/" + subscriptionId.toString()
                    + "/services/sqlservers/servers/" + server + "/databases/" + database + "'}},"
                    + "'InternalResources':{'ZumoMobileService':{'ProvisioningParameters'" + ":{'Name':'"
                    + serviceName + "','Location':'" + region
                    + "'},'ProvisioningConfigParameters':{'Server':{'StringConcat':[{'ResourceReference':'ZumoSqlServer_"
                    + zumoServerId + ".Name'},"
                    + "'.database.windows.net']},'Database':{'ResourceReference':'ZumoSqlDatabase_" + zumoDBId
                    + ".Name'},'AdministratorLogin':" + "'" + username + "','AdministratorLoginPassword':'"
                    + password + "'},'Version':'2012-05-21.1.0','Name':'ZumoMobileService','Type':"
                    + "'Microsoft.WindowsAzure.MobileServices.MobileService'}}}";
        }

        String xmlParameter = String.format(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?><Application xmlns=\"http://schemas.microsoft.com/windowsazure\"><Name>%s</Name>"
                        + "<Label>%s</Label><Description>%s</Description><Configuration>%s</Configuration></Application>",
                serviceName + "mobileservice", serviceName, serviceName,
                new BASE64Encoder().encode(JSONParameter.getBytes()));

        AzureRestAPIHelper.postRestApiCommand(path, xmlParameter, subscriptionId.toString(),
                String.format("/%s/operations/", subscriptionId.toString()), false);

        String xml = AzureRestAPIHelper.getRestApiCommand(
                String.format("/%s/applications/%s", subscriptionId.toString(), serviceName + "mobileservice"),
                subscriptionId.toString());
        NodeList statusNode = ((NodeList) XmlHelper.getXMLValue(xml, "//Application/State",
                XPathConstants.NODESET));

        if (statusNode.getLength() > 0 && statusNode.item(0).getTextContent().equals("Healthy")) {
            return;
        } else {
            deleteService(subscriptionId, serviceName);

            String errors = ((String) XmlHelper.getXMLValue(xml, "//FailureCode[text()]",
                    XPathConstants.STRING));
            String errorMessage = ((String) XmlHelper.getXMLValue(errors, "//Message[text()]",
                    XPathConstants.STRING));
            throw new AzureCmdException("Error creating service", errorMessage);
        }
    } catch (Throwable t) {
        if (t instanceof AzureCmdException) {
            throw (AzureCmdException) t;
        } else {
            throw new AzureCmdException("Error creating service", t);
        }
    }
}

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

@Override
public void createMobileService(@NotNull String subscriptionId, @NotNull String region,
        @NotNull String username, @NotNull String password, @NotNull String mobileServiceName,
        @Nullable String server, @Nullable String database) throws AzureCmdException {
    try {//  w ww  .j  a v  a  2 s .c om
        String path = String.format("/%s/applications", subscriptionId);

        String JSONParameter;

        if (database == null || server == null) {
            String zumoServerId = UUID.randomUUID().toString().replace("-", "");
            String zumoDBId = UUID.randomUUID().toString().replace("-", "");
            String dbName = mobileServiceName + "_db";

            JSONParameter = "{'SchemaVersion':'2012-05.1.0','Location':'" + region
                    + "','ExternalResources':{},'InternalResources':{'ZumoMobileService':"
                    + "{'ProvisioningParameters':{'Name':'" + mobileServiceName + "','Location':'" + region
                    + "'},'ProvisioningConfigParameters':{'Server':{'StringConcat':"
                    + "[{'ResourceReference':'ZumoSqlServer_" + zumoServerId
                    + ".Name'},'.database.windows.net']},'Database':{'ResourceReference':'ZumoSqlDatabase_"
                    + zumoDBId + ".Name'},'AdministratorLogin':'" + username
                    + "','AdministratorLoginPassword':'" + password + "'},'Version':'2012-05-21.1.0',"
                    + "'Name':'ZumoMobileService','Type':'Microsoft.WindowsAzure.MobileServices.MobileService'},'ZumoSqlServer_"
                    + zumoServerId + "':{'ProvisioningParameters':{'AdministratorLogin':'" + username
                    + "','AdministratorLoginPassword':'" + password + "','Location':'" + region
                    + "'},'ProvisioningConfigParameters':{'FirewallRules':[{'Name':'AllowAllWindowsAzureIps','StartIPAddress':'0.0.0.0','EndIPAddress':'0.0.0.0'}]},"
                    + "'Version':'1.0','Name':'ZumoSqlServer_" + zumoServerId
                    + "','Type':'Microsoft.WindowsAzure.SQLAzure.Server'},'ZumoSqlDatabase_" + zumoDBId
                    + "':{'ProvisioningParameters':{'Name':'" + dbName
                    + "','Edition':'WEB','MaxSizeInGB':'1','DBServer':{'ResourceReference':'ZumoSqlServer_"
                    + zumoServerId
                    + ".Name'},'CollationName':'SQL_Latin1_General_CP1_CI_AS'},'Version':'1.0','Name':'ZumoSqlDatabase_"
                    + zumoDBId + "','Type':'Microsoft.WindowsAzure.SQLAzure.DataBase'}}}";
        } else {
            String zumoServerId = UUID.randomUUID().toString().replace("-", "");
            String zumoDBId = UUID.randomUUID().toString().replace("-", "");

            JSONParameter = "{'SchemaVersion':'2012-05.1.0','Location':'West US','ExternalResources':{'ZumoSqlServer_"
                    + zumoServerId + "':{'Name':'ZumoSqlServer_" + zumoServerId + "',"
                    + "'Type':'Microsoft.WindowsAzure.SQLAzure.Server','URI':'https://management.core.windows.net:8443/"
                    + subscriptionId + "/services/sqlservers/servers/" + server + "'}," + "'ZumoSqlDatabase_"
                    + zumoDBId + "':{'Name':'ZumoSqlDatabase_" + zumoDBId
                    + "','Type':'Microsoft.WindowsAzure.SQLAzure.DataBase',"
                    + "'URI':'https://management.core.windows.net:8443/" + subscriptionId
                    + "/services/sqlservers/servers/" + server + "/databases/" + database + "'}},"
                    + "'InternalResources':{'ZumoMobileService':{'ProvisioningParameters'" + ":{'Name':'"
                    + mobileServiceName + "','Location':'" + region
                    + "'},'ProvisioningConfigParameters':{'Server':{'StringConcat':[{'ResourceReference':'ZumoSqlServer_"
                    + zumoServerId + ".Name'},"
                    + "'.database.windows.net']},'Database':{'ResourceReference':'ZumoSqlDatabase_" + zumoDBId
                    + ".Name'},'AdministratorLogin':" + "'" + username + "','AdministratorLoginPassword':'"
                    + password + "'},'Version':'2012-05-21.1.0','Name':'ZumoMobileService','Type':"
                    + "'Microsoft.WindowsAzure.MobileServices.MobileService'}}}";
        }

        String xmlParameter = String.format(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?><Application xmlns=\"http://schemas.microsoft.com/windowsazure\"><Name>%s</Name>"
                        + "<Label>%s</Label><Description>%s</Description><Configuration>%s</Configuration></Application>",
                mobileServiceName + "mobileservice", mobileServiceName, mobileServiceName,
                new BASE64Encoder().encode(JSONParameter.getBytes()));

        executePollRequest(subscriptionId, path, ContentType.Xml, "POST", xmlParameter,
                String.format("/%s/operations/", subscriptionId));

        String xml = executeGetRequest(subscriptionId,
                String.format("/%s/applications/%s", subscriptionId, mobileServiceName + "mobileservice"));
        NodeList statusNode = ((NodeList) XmlHelper.getXMLValue(xml, "//Application/State",
                XPathConstants.NODESET));

        if (!(statusNode.getLength() > 0 && statusNode.item(0).getTextContent().equals("Healthy"))) {
            deleteMobileService(subscriptionId, mobileServiceName);

            String errors = ((String) XmlHelper.getXMLValue(xml, "//FailureCode[text()]",
                    XPathConstants.STRING));
            String errorMessage = ((String) XmlHelper.getXMLValue(errors, "//Message[text()]",
                    XPathConstants.STRING));
            throw new AzureCmdException("Error creating service", errorMessage);
        }
    } catch (Throwable t) {
        if (t instanceof AzureCmdException) {
            throw (AzureCmdException) t;
        }

        throw new AzureCmdException("Error creating service", t);
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

public void checkPropFindSupportedCalendarComponentSet(Account user, String fullurl, String shorturl,
        String[] compNames) throws Exception {
    PropFindMethod method = new PropFindMethod(fullurl);
    addBasicAuthHeaderForUser(method, user);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    String respBody;/*from  w  w  w .  j  a  va2s  . c  o  m*/
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(new ByteArrayRequestEntity(propFindSupportedCalendarComponentSet.getBytes(),
            MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;
    String text;
    NodeList result;
    xPathExpr = xpath.compile("/D:multistatus/D:response/D:href/text()");
    result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
    text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
    assertEquals("HREF", shorturl.replaceAll("@", "%40"), text);
    xPathExpr = xpath.compile("/D:multistatus/D:response/D:propstat/D:status/text()");
    text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
    assertEquals("status", "HTTP/1.1 200 OK", text);
    xPathExpr = xpath
            .compile("/D:multistatus/D:response/D:propstat/D:prop/C:supported-calendar-component-set/C:comp");
    result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
    assertEquals("Number of comp nodes under supported-calendar-component-set", compNames.length,
            result.getLength());
    List<String> names = Arrays.asList(compNames);
    for (int ndx = 0; ndx < result.getLength(); ndx++) {
        org.w3c.dom.Element child = (org.w3c.dom.Element) result.item(ndx);
        String name = child.getAttribute("name");
        assertNotNull("comp should have a 'name' attribute", name);
        assertTrue(String.format("comp 'name' attribute '%s' should be one of the expected names", name),
                names.contains(name));
    }
}