Example usage for javax.xml.bind DatatypeConverter parseBoolean

List of usage examples for javax.xml.bind DatatypeConverter parseBoolean

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseBoolean.

Prototype

public static boolean parseBoolean(String lexicalXSDBoolean) 

Source Link

Document

Converts the string argument into a boolean value.

Usage

From source file:br.com.upic.camel.openedge.OpenEdgeEndpoint.java

@Override
protected void onExchange(final Exchange exchange) throws Exception {

    try {/*  w ww.j av  a 2  s  .c o m*/
        LOG.info("Unmarshalling the request");

        final Request req = (Request) unmarshaller.unmarshal(exchange.getIn().getBody(Document.class));

        LOG.info("Setting the input params");

        final List<JAXBElement<? extends Serializable>> reqParamElementList = req.getParamElementList();

        final ParamArray proParams = new ParamArray(reqParamElementList.size());

        for (final JAXBElement<? extends Serializable> reqParamElement : reqParamElementList) {
            final Serializable reqParam = reqParamElement.getValue();

            if (reqParam instanceof CharArrayParam) {
                final CharArrayParam charArrayParam = (CharArrayParam) reqParam;

                final ParamMode mode = charArrayParam.getMode();

                final int id = charArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<String> value = new ArrayList<String>();

                    for (final JAXBElement<String> valueElement : charArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseString(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addCharacterArray(id, value.toArray(new String[] {}), mode.value(), value.size());
                } else {
                    proParams.addCharacterArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof CharParam) {
                final CharParam charParam = (CharParam) reqParam;

                final ParamMode mode = charParam.getMode();

                final int id = charParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addCharacter(id, DatatypeConverter.parseString(charParam.getContent()),
                            mode.value());
                else
                    proParams.addCharacter(id, null, mode.value());

            } else if (reqParam instanceof DateArrayParam) {
                final DateArrayParam dateArrayParam = (DateArrayParam) reqParam;

                final ParamMode mode = dateArrayParam.getMode();

                final int id = dateArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>();

                    for (final JAXBElement<String> valueElement : dateArrayParam.getValueElementList()) {

                        if (!valueElement.isNil()) {
                            final GregorianCalendar cal = new GregorianCalendar();

                            cal.setTime(DatatypeConverter.parseDate(valueElement.getValue()).getTime());

                            value.add(cal);
                        } else {
                            value.add(null);
                        }

                    }

                    proParams.addDateArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDateArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DateParam) {
                final DateParam dateParam = (DateParam) reqParam;

                final ParamMode mode = dateParam.getMode();

                final int id = dateParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final GregorianCalendar cal = new GregorianCalendar();

                    cal.setTime(DatatypeConverter.parseDate(dateParam.getContent()).getTime());

                    proParams.addDate(id, cal, mode.value());
                } else {
                    proParams.addDate(id, null, mode.value());
                }

            } else if (reqParam instanceof DateTimeArrayParam) {
                final DateTimeArrayParam dateTimeArrayParam = (DateTimeArrayParam) reqParam;

                final ParamMode mode = dateTimeArrayParam.getMode();

                final int id = dateTimeArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>();

                    for (final JAXBElement<String> valueElement : dateTimeArrayParam.getValueElementList()) {

                        if (!valueElement.isNil()) {
                            final GregorianCalendar cal = new GregorianCalendar();

                            cal.setTime(DatatypeConverter.parseDateTime(valueElement.getValue()).getTime());

                            value.add(cal);
                        } else {
                            value.add(null);
                        }

                    }

                    proParams.addDatetimeArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDatetimeArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DateTimeParam) {
                final DateTimeParam dateTimeParam = (DateTimeParam) reqParam;

                final ParamMode mode = dateTimeParam.getMode();

                final int id = dateTimeParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final GregorianCalendar cal = new GregorianCalendar();

                    cal.setTime(DatatypeConverter.parseDateTime(dateTimeParam.getContent()).getTime());

                    proParams.addDatetime(id, cal, mode.value());
                } else {
                    proParams.addDatetime(id, null, mode.value());
                }

            } else if (reqParam instanceof DateTimeTZArrayParam) {
                final DateTimeTZArrayParam dateTimeTZArrayParam = (DateTimeTZArrayParam) reqParam;

                final ParamMode mode = dateTimeTZArrayParam.getMode();

                final int id = dateTimeTZArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>();

                    for (final JAXBElement<String> valueElement : dateTimeTZArrayParam.getValueElementList()) {

                        if (!valueElement.isNil()) {
                            final GregorianCalendar cal = new GregorianCalendar();

                            cal.setTime(DatatypeConverter.parseDateTime(valueElement.getValue()).getTime());

                            value.add(cal);
                        } else {
                            value.add(null);
                        }

                    }

                    proParams.addDatetimeTZArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDatetimeTZArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DateTimeTZParam) {
                final DateTimeTZParam dateTimeTZParam = (DateTimeTZParam) reqParam;

                final ParamMode mode = dateTimeTZParam.getMode();

                final int id = dateTimeTZParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final GregorianCalendar cal = new GregorianCalendar();

                    cal.setTime(DatatypeConverter.parseDateTime(dateTimeTZParam.getContent()).getTime());

                    proParams.addDatetimeTZ(id, cal, mode.value());
                } else {
                    proParams.addDatetimeTZ(id, null, mode.value());
                }

            } else if (reqParam instanceof DecArrayParam) {
                final DecArrayParam decArrayParam = (DecArrayParam) reqParam;

                final ParamMode mode = decArrayParam.getMode();

                final int id = decArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<BigDecimal> value = new ArrayList<BigDecimal>();

                    for (final JAXBElement<String> valueElement : decArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseDecimal(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addDecimalArray(id, value.toArray(new BigDecimal[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDecimalArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DecParam) {
                final DecParam decParam = (DecParam) reqParam;

                final ParamMode mode = decParam.getMode();

                final int id = decParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addDecimal(id, DatatypeConverter.parseDecimal(decParam.getContent()),
                            mode.value());
                else
                    proParams.addDecimal(id, null, mode.value());

            } else if (reqParam instanceof IntArrayParam) {
                final IntArrayParam intArrayParam = (IntArrayParam) reqParam;

                final ParamMode mode = intArrayParam.getMode();

                final int id = intArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<Integer> value = new ArrayList<Integer>();

                    for (final JAXBElement<String> valueElement : intArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseInt(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addIntegerArray(id, value.toArray(new Integer[] {}), mode.value(), value.size());
                } else {
                    proParams.addIntegerArray(id, (Integer[]) null, mode.value(), 0);
                }

            } else if (reqParam instanceof IntParam) {
                final IntParam intParam = (IntParam) reqParam;

                final ParamMode mode = intParam.getMode();

                final int id = intParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addInteger(id, new Integer(DatatypeConverter.parseInt(intParam.getContent())),
                            mode.value());
                else
                    proParams.addInteger(id, null, mode.value());

            } else if (reqParam instanceof LogArrayParam) {
                final LogArrayParam logArrayParam = (LogArrayParam) reqParam;

                final ParamMode mode = logArrayParam.getMode();

                final int id = logArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<Boolean> value = new ArrayList<Boolean>();

                    for (final JAXBElement<String> valueElement : logArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseBoolean(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addLogicalArray(id, value.toArray(new Boolean[] {}), mode.value(), value.size());
                } else {
                    proParams.addLogicalArray(id, (Boolean[]) null, mode.value(), 0);
                }

            } else if (reqParam instanceof LogParam) {
                final LogParam logParam = (LogParam) reqParam;

                final ParamMode mode = logParam.getMode();

                final int id = logParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addLogical(id, new Boolean(DatatypeConverter.parseBoolean(logParam.getContent())),
                            mode.value());
                else
                    proParams.addLogical(id, null, mode.value());

            } else if (reqParam instanceof ResultSetParam) {
                final ResultSetParam rsParam = (ResultSetParam) reqParam;

                final ParamMode mode = rsParam.getMode();

                final int id = rsParam.getId();

                final ResultSetMetaData rsMetaData = rsParam.getResultSetMetaData();

                final List<Serializable> fieldMetaDataList = rsMetaData.getFieldMetaDataList();

                final ProResultSetMetaDataImpl proRsMetaData = new ProResultSetMetaDataImpl(
                        fieldMetaDataList.size());

                for (final Serializable fieldMetaData : fieldMetaDataList) {

                    if (fieldMetaData instanceof CharFieldMetaData) {
                        final CharFieldMetaData charFieldMetaData = (CharFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(charFieldMetaData.getId(), charFieldMetaData.getName(),
                                charFieldMetaData.getExtent(), Parameter.PRO_CHARACTER);
                    } else if (fieldMetaData instanceof DateFieldMetaData) {
                        final DateFieldMetaData dateFieldMetaData = (DateFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(dateFieldMetaData.getId(), dateFieldMetaData.getName(),
                                dateFieldMetaData.getExtent(), Parameter.PRO_DATE);
                    } else if (fieldMetaData instanceof DateTimeFieldMetaData) {
                        final DateTimeFieldMetaData dateTimeFieldMetaData = (DateTimeFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(dateTimeFieldMetaData.getId(),
                                dateTimeFieldMetaData.getName(), dateTimeFieldMetaData.getExtent(),
                                Parameter.PRO_DATETIME);
                    } else if (fieldMetaData instanceof DateTimeTZFieldMetaData) {
                        final DateTimeTZFieldMetaData dateTimeTZFieldMetaData = (DateTimeTZFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(dateTimeTZFieldMetaData.getId(),
                                dateTimeTZFieldMetaData.getName(), dateTimeTZFieldMetaData.getExtent(),
                                Parameter.PRO_DATETIMETZ);
                    } else if (fieldMetaData instanceof DecFieldMetaData) {
                        final DecFieldMetaData decFieldMetaData = (DecFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(decFieldMetaData.getId(), decFieldMetaData.getName(),
                                decFieldMetaData.getExtent(), Parameter.PRO_DECIMAL);
                    } else if (fieldMetaData instanceof IntFieldMetaData) {
                        final IntFieldMetaData intFieldMetaData = (IntFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(intFieldMetaData.getId(), intFieldMetaData.getName(),
                                intFieldMetaData.getExtent(), Parameter.PRO_INTEGER);
                    } else if (fieldMetaData instanceof LogFieldMetaData) {
                        final LogFieldMetaData logFieldMetaData = (LogFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(logFieldMetaData.getId(), logFieldMetaData.getName(),
                                logFieldMetaData.getExtent(), Parameter.PRO_LOGICAL);
                    }

                }

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addTable(id, new OpenEdgeResultSet(rsParam.getRowList().iterator()), mode.value(),
                            proRsMetaData);
                else
                    proParams.addTable(id, null, mode.value(), proRsMetaData);

            }

        }

        LOG.info("Connecting to the AppServer");

        if (SESSION_MODEL_MANAGED == sessionModel)
            RunTimeProperties.setSessionModel(0);
        else if (SESSION_MODEL_FREE == sessionModel)
            RunTimeProperties.setSessionModel(1);

        final OpenAppObject proAppObject = new OpenAppObject(url, user, password, null, null);

        proAppObject.runProc(req.getProgram(), proParams);

        LOG.info("Marshalling the response");

        final Response res = OBJECT_FACTORY.createResponse();

        res.setResult(proParams.getProcReturnString());

        LOG.info("Setting the output params");

        for (final JAXBElement<? extends Serializable> reqParamElement : reqParamElementList) {
            final Serializable reqParam = reqParamElement.getValue();

            if (reqParam instanceof CharArrayParam) {
                final CharArrayParam reqCharArrayParam = (CharArrayParam) reqParam;

                if (ParamMode.INPUT != reqCharArrayParam.getMode()) {
                    final JAXBElement<CharArrayParam> resParamElement = new JAXBElement<CharArrayParam>(
                            new QName(NS, "CharArray"), CharArrayParam.class, null);

                    final CharArrayParam resParam = OBJECT_FACTORY.createCharArrayParam();

                    resParam.setId(reqCharArrayParam.getId());

                    resParam.setName(reqCharArrayParam.getName());

                    final String[] proParam = (String[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printString(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof CharParam) {
                final CharParam reqCharParam = (CharParam) reqParam;

                if (ParamMode.INPUT != reqCharParam.getMode()) {
                    final JAXBElement<CharParam> resParamElement = new JAXBElement<CharParam>(
                            new QName(NS, "Char"), CharParam.class, null);

                    final CharParam resParam = OBJECT_FACTORY.createCharParam();

                    resParam.setId(reqCharParam.getId());

                    resParam.setName(reqCharParam.getName());

                    final String proParam = (String) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printString(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateArrayParam) {
                final DateArrayParam reqDateArrayParam = (DateArrayParam) reqParam;

                if (ParamMode.INPUT != reqDateArrayParam.getMode()) {
                    final JAXBElement<DateArrayParam> resParamElement = new JAXBElement<DateArrayParam>(
                            new QName(NS, "DateArray"), DateArrayParam.class, null);

                    final DateArrayParam resParam = OBJECT_FACTORY.createDateArrayParam();

                    resParam.setId(reqDateArrayParam.getId());

                    resParam.setName(reqDateArrayParam.getName());

                    final Date[] proParam = (Date[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null) {
                                final Calendar cal = Calendar.getInstance();

                                cal.setTime(proParam[i]);

                                valueElement.setValue(DatatypeConverter.printDate(cal));
                            } else {
                                valueElement.setNil(true);
                            }

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateParam) {
                final DateParam reqDateParam = (DateParam) reqParam;

                if (ParamMode.INPUT != reqDateParam.getMode()) {
                    final JAXBElement<DateParam> resParamElement = new JAXBElement<DateParam>(
                            new QName(NS, "Date"), DateParam.class, null);

                    final DateParam resParam = OBJECT_FACTORY.createDateParam();

                    resParam.setId(reqDateParam.getId());

                    resParam.setName(reqDateParam.getName());

                    final Date proParam = (Date) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        final Calendar cal = Calendar.getInstance();

                        cal.setTime(proParam);

                        resParam.setContent(DatatypeConverter.printDate(cal));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeArrayParam) {
                final DateTimeArrayParam reqDateTimeArrayParam = (DateTimeArrayParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeArrayParam.getMode()) {
                    final JAXBElement<DateTimeArrayParam> resParamElement = new JAXBElement<DateTimeArrayParam>(
                            new QName(NS, "DateTimeArray"), DateTimeArrayParam.class, null);

                    final DateTimeArrayParam resParam = OBJECT_FACTORY.createDateTimeArrayParam();

                    resParam.setId(reqDateTimeArrayParam.getId());

                    resParam.setName(reqDateTimeArrayParam.getName());

                    final GregorianCalendar[] proParam = (GregorianCalendar[]) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printDateTime(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeParam) {
                final DateTimeParam reqDateTimeParam = (DateTimeParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeParam.getMode()) {
                    final JAXBElement<DateTimeParam> resParamElement = new JAXBElement<DateTimeParam>(
                            new QName(NS, "DateTime"), DateTimeParam.class, null);

                    final DateTimeParam resParam = OBJECT_FACTORY.createDateTimeParam();

                    resParam.setId(reqDateTimeParam.getId());

                    resParam.setName(reqDateTimeParam.getName());

                    final GregorianCalendar proParam = (GregorianCalendar) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printDateTime(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeTZArrayParam) {
                final DateTimeTZArrayParam reqDateTimeTZArrayParam = (DateTimeTZArrayParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeTZArrayParam.getMode()) {
                    final JAXBElement<DateTimeTZArrayParam> resParamElement = new JAXBElement<DateTimeTZArrayParam>(
                            new QName(NS, "DateTimeTZArray"), DateTimeTZArrayParam.class, null);

                    final DateTimeTZArrayParam resParam = OBJECT_FACTORY.createDateTimeTZArrayParam();

                    resParam.setId(reqDateTimeTZArrayParam.getId());

                    resParam.setName(reqDateTimeTZArrayParam.getName());

                    final GregorianCalendar[] proParam = (GregorianCalendar[]) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printDateTime(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeTZParam) {
                final DateTimeTZParam reqDateTimeTZParam = (DateTimeTZParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeTZParam.getMode()) {
                    final JAXBElement<DateTimeTZParam> resParamElement = new JAXBElement<DateTimeTZParam>(
                            new QName(NS, "DateTimeTZ"), DateTimeTZParam.class, null);

                    final DateTimeTZParam resParam = OBJECT_FACTORY.createDateTimeTZParam();

                    resParam.setId(reqDateTimeTZParam.getId());

                    resParam.setName(reqDateTimeTZParam.getName());

                    final GregorianCalendar proParam = (GregorianCalendar) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printDateTime(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DecArrayParam) {
                final DecArrayParam reqDecArrayParam = (DecArrayParam) reqParam;

                if (ParamMode.INPUT != reqDecArrayParam.getMode()) {
                    final JAXBElement<DecArrayParam> resParamElement = new JAXBElement<DecArrayParam>(
                            new QName(NS, "DecArray"), DecArrayParam.class, null);

                    final DecArrayParam resParam = OBJECT_FACTORY.createDecArrayParam();

                    resParam.setId(reqDecArrayParam.getId());

                    resParam.setName(reqDecArrayParam.getName());

                    final BigDecimal[] proParam = (BigDecimal[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printDecimal(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DecParam) {
                final DecParam reqDecParam = (DecParam) reqParam;

                if (ParamMode.INPUT != reqDecParam.getMode()) {
                    final JAXBElement<DecParam> resParamElement = new JAXBElement<DecParam>(
                            new QName(NS, "Dec"), DecParam.class, null);

                    final DecParam resParam = OBJECT_FACTORY.createDecParam();

                    resParam.setId(reqDecParam.getId());

                    resParam.setName(reqDecParam.getName());

                    final BigDecimal proParam = (BigDecimal) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printDecimal(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof IntArrayParam) {
                final IntArrayParam reqIntArrayParam = (IntArrayParam) reqParam;

                if (ParamMode.INPUT != reqIntArrayParam.getMode()) {
                    final JAXBElement<IntArrayParam> resParamElement = new JAXBElement<IntArrayParam>(
                            new QName(NS, "IntArray"), IntArrayParam.class, null);

                    final IntArrayParam resParam = OBJECT_FACTORY.createIntArrayParam();

                    resParam.setId(reqIntArrayParam.getId());

                    resParam.setName(reqIntArrayParam.getName());

                    final Integer[] proParam = (Integer[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printInt(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof IntParam) {
                final IntParam reqIntParam = (IntParam) reqParam;

                if (ParamMode.INPUT != reqIntParam.getMode()) {
                    final JAXBElement<IntParam> resParamElement = new JAXBElement<IntParam>(
                            new QName(NS, "Int"), IntParam.class, null);

                    final IntParam resParam = OBJECT_FACTORY.createIntParam();

                    resParam.setId(reqIntParam.getId());

                    resParam.setName(reqIntParam.getName());

                    final Integer proParam = (Integer) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printInt(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof LogArrayParam) {
                final LogArrayParam reqLogArrayParam = (LogArrayParam) reqParam;

                if (ParamMode.INPUT != reqLogArrayParam.getMode()) {
                    final JAXBElement<LogArrayParam> resParamElement = new JAXBElement<LogArrayParam>(
                            new QName(NS, "LogArray"), LogArrayParam.class, null);

                    final LogArrayParam resParam = OBJECT_FACTORY.createLogArrayParam();

                    resParam.setId(reqLogArrayParam.getId());

                    resParam.setName(reqLogArrayParam.getName());

                    final Boolean[] proParam = (Boolean[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printBoolean(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof LogParam) {
                final LogParam reqLogParam = (LogParam) reqParam;

                if (ParamMode.INPUT != reqLogParam.getMode()) {
                    final JAXBElement<LogParam> resParamElement = new JAXBElement<LogParam>(
                            new QName(NS, "Log"), LogParam.class, null);

                    final LogParam resParam = OBJECT_FACTORY.createLogParam();

                    resParam.setId(reqLogParam.getId());

                    resParam.setName(reqLogParam.getName());

                    final Boolean proParam = (Boolean) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printBoolean(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof ResultSetParam) {
                final ResultSetParam reqResultSetParam = (ResultSetParam) reqParam;

                if (ParamMode.INPUT != reqResultSetParam.getMode()) {
                    final JAXBElement<ResultSetParam> resParamElement = new JAXBElement<ResultSetParam>(
                            new QName(NS, "ResultSet"), ResultSetParam.class, null);

                    final ResultSetParam resParam = OBJECT_FACTORY.createResultSetParam();

                    resParam.setId(reqResultSetParam.getId());

                    resParam.setName(reqResultSetParam.getName());

                    final ProResultSet proParam = (ProResultSet) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        while (proParam.next()) {
                            final Row row = OBJECT_FACTORY.createRow();

                            final ResultSetMetaData rsMetaData = reqResultSetParam.getResultSetMetaData();

                            for (final Serializable fieldMetaData : rsMetaData.getFieldMetaDataList()) {

                                if (fieldMetaData instanceof CharFieldMetaData) {
                                    final CharFieldMetaData charFieldMetaData = (CharFieldMetaData) fieldMetaData;

                                    final int extent = charFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<CharField> fieldElement = new JAXBElement<CharField>(
                                                new QName(NS, "Char"), CharField.class, null);

                                        final CharField field = OBJECT_FACTORY.createCharField();

                                        field.setId(charFieldMetaData.getId());

                                        field.setName(charFieldMetaData.getName());

                                        final String value = proParam.getString(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printString(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<CharField> fieldElement = new JAXBElement<CharField>(
                                                    new QName(NS, "Char"), CharField.class, null);

                                            final CharField field = OBJECT_FACTORY.createCharField();

                                            field.setId(charFieldMetaData.getId());

                                            field.setName(charFieldMetaData.getName());

                                            final String value = proParam.getString(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printString(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DateFieldMetaData) {
                                    final DateFieldMetaData dateFieldMetaData = (DateFieldMetaData) fieldMetaData;

                                    final int extent = dateFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DateField> fieldElement = new JAXBElement<DateField>(
                                                new QName(NS, "Date"), DateField.class, null);

                                        final DateField field = OBJECT_FACTORY.createDateField();

                                        field.setId(dateFieldMetaData.getId());

                                        field.setName(dateFieldMetaData.getName());

                                        final Date value = proParam.getDate(field.getId());

                                        if (value != null) {
                                            final Calendar cal = Calendar.getInstance();

                                            cal.setTime(value);

                                            field.setContent(DatatypeConverter.printDate(cal));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DateField> fieldElement = new JAXBElement<DateField>(
                                                    new QName(NS, "Date"), DateField.class, null);

                                            final DateField field = OBJECT_FACTORY.createDateField();

                                            field.setId(dateFieldMetaData.getId());

                                            field.setName(dateFieldMetaData.getName());

                                            final Date value = proParam.getDate(field.getId(), i);

                                            if (value != null) {
                                                final Calendar cal = Calendar.getInstance();

                                                cal.setTime(value);

                                                field.setContent(DatatypeConverter.printDate(cal));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DateTimeFieldMetaData) {
                                    final DateTimeFieldMetaData dateTimeFieldMetaData = (DateTimeFieldMetaData) fieldMetaData;

                                    final int extent = dateTimeFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DateTimeField> fieldElement = new JAXBElement<DateTimeField>(
                                                new QName(NS, "DateTime"), DateTimeField.class, null);

                                        final DateTimeField field = OBJECT_FACTORY.createDateTimeField();

                                        field.setId(dateTimeFieldMetaData.getId());

                                        field.setName(dateTimeFieldMetaData.getName());

                                        final GregorianCalendar value = (GregorianCalendar) proParam
                                                .getObject(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printDateTime(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DateTimeField> fieldElement = new JAXBElement<DateTimeField>(
                                                    new QName(NS, "DateTime"), DateTimeField.class, null);

                                            final DateTimeField field = OBJECT_FACTORY.createDateTimeField();

                                            field.setId(dateTimeFieldMetaData.getId());

                                            field.setName(dateTimeFieldMetaData.getName());

                                            final GregorianCalendar value = (GregorianCalendar) proParam
                                                    .getObject(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printDateTime(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DateTimeTZFieldMetaData) {
                                    final DateTimeTZFieldMetaData dateTimeTZFieldMetaData = (DateTimeTZFieldMetaData) fieldMetaData;

                                    final int extent = dateTimeTZFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DateTimeTZField> fieldElement = new JAXBElement<DateTimeTZField>(
                                                new QName(NS, "DateTimeTZ"), DateTimeTZField.class, null);

                                        final DateTimeTZField field = OBJECT_FACTORY.createDateTimeTZField();

                                        field.setId(dateTimeTZFieldMetaData.getId());

                                        field.setName(dateTimeTZFieldMetaData.getName());

                                        final GregorianCalendar value = (GregorianCalendar) proParam
                                                .getObject(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printDateTime(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DateTimeTZField> fieldElement = new JAXBElement<DateTimeTZField>(
                                                    new QName(NS, "DateTimeTZ"), DateTimeTZField.class, null);

                                            final DateTimeTZField field = OBJECT_FACTORY
                                                    .createDateTimeTZField();

                                            field.setId(dateTimeTZFieldMetaData.getId());

                                            field.setName(dateTimeTZFieldMetaData.getName());

                                            final GregorianCalendar value = (GregorianCalendar) proParam
                                                    .getObject(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printDateTime(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DecFieldMetaData) {
                                    final DecFieldMetaData decFieldMetaData = (DecFieldMetaData) fieldMetaData;

                                    final int extent = decFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DecField> fieldElement = new JAXBElement<DecField>(
                                                new QName(NS, "Dec"), DecField.class, null);

                                        final DecField field = OBJECT_FACTORY.createDecField();

                                        field.setId(decFieldMetaData.getId());

                                        field.setName(decFieldMetaData.getName());

                                        final BigDecimal value = proParam.getBigDecimal(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printDecimal(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DecField> fieldElement = new JAXBElement<DecField>(
                                                    new QName(NS, "Dec"), DecField.class, null);

                                            final DecField field = OBJECT_FACTORY.createDecField();

                                            field.setId(decFieldMetaData.getId());

                                            field.setName(decFieldMetaData.getName());

                                            final BigDecimal value = proParam.getBigDecimal(field.getId(), i,
                                                    0);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printDecimal(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof IntFieldMetaData) {
                                    final IntFieldMetaData intFieldMetaData = (IntFieldMetaData) fieldMetaData;

                                    final int extent = intFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<IntField> fieldElement = new JAXBElement<IntField>(
                                                new QName(NS, "Int"), IntField.class, null);

                                        final IntField field = OBJECT_FACTORY.createIntField();

                                        field.setId(intFieldMetaData.getId());

                                        field.setName(intFieldMetaData.getName());

                                        final String value = proParam.getString(field.getId());

                                        if (value != null) {
                                            field.setContent(
                                                    DatatypeConverter.printInt(Integer.parseInt(value)));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<IntField> fieldElement = new JAXBElement<IntField>(
                                                    new QName(NS, "Int"), IntField.class, null);

                                            final IntField field = OBJECT_FACTORY.createIntField();

                                            field.setId(intFieldMetaData.getId());

                                            field.setName(intFieldMetaData.getName());

                                            final String value = proParam.getString(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(
                                                        DatatypeConverter.printInt(Integer.parseInt(value)));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof LogFieldMetaData) {
                                    final LogFieldMetaData logFieldMetaData = (LogFieldMetaData) fieldMetaData;

                                    final int extent = logFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<LogField> fieldElement = new JAXBElement<LogField>(
                                                new QName(NS, "Log"), LogField.class, null);

                                        final LogField field = OBJECT_FACTORY.createLogField();

                                        field.setId(logFieldMetaData.getId());

                                        field.setName(logFieldMetaData.getName());

                                        final String value = proParam.getString(field.getId());

                                        if (value != null) {
                                            field.setContent(
                                                    DatatypeConverter.printBoolean(Boolean.valueOf(value)));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<LogField> fieldElement = new JAXBElement<LogField>(
                                                    new QName(NS, "Log"), LogField.class, null);

                                            final LogField field = OBJECT_FACTORY.createLogField();

                                            field.setId(logFieldMetaData.getId());

                                            field.setName(logFieldMetaData.getName());

                                            final String value = proParam.getString(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(
                                                        DatatypeConverter.printBoolean(Boolean.valueOf(value)));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                }

                            }

                            resParam.getRowList().add(row);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            }

        }

        final Document doc = builder.newDocument();

        marshaller.marshal(res, doc);

        exchange.getOut().setBody(doc);
    } catch (final RunTime4GLErrorException e) {
        LOG.error(e.getProcReturnString(), e);

        throw new OpenEdgeException(e.getProcReturnString(), e);
    }

}

From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java

/**
* The Check Name Availability operation checks if a storage account name is
* available for use in Azure.  (see//w  ww .  ja  v  a2 s .  co m
* http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx for
* more information)
*
* @param accountName Required. The desired storage account name to check
* for availability.
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The response to a storage account check name availability request.
*/
@Override
public CheckNameAvailabilityResponse checkNameAvailability(String accountName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (accountName == null) {
        throw new NullPointerException("accountName");
    }

    // 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("accountName", accountName);
        CloudTracing.enter(invocationId, this, "checkNameAvailabilityAsync", 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/storageservices/operations/isavailable/";
    url = url + URLEncoder.encode(accountName, "UTF-8");
    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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2014-10-01");

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element availabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "AvailabilityResponse");
            if (availabilityResponseElement != null) {
                Element resultElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "Result");
                if (resultElement != null) {
                    boolean resultInstance;
                    resultInstance = DatatypeConverter
                            .parseBoolean(resultElement.getTextContent().toLowerCase());
                    result.setIsAvailable(resultInstance);
                }

                Element reasonElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "Reason");
                if (reasonElement != null) {
                    boolean isNil = false;
                    Attr nilAttribute = reasonElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute != null) {
                        isNil = "true".equals(nilAttribute.getValue());
                    }
                    if (isNil == false) {
                        String reasonInstance;
                        reasonInstance = reasonElement.getTextContent();
                        result.setReason(reasonInstance);
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.compute.OperatingSystemOperationsImpl.java

/**
* The List OS Families operation lists the guest operating system families
* available in Azure, and also lists the operating system versions
* available for each family. Currently Azure supports two operating system
* families: the Azure guest operating system that is substantially
* compatible with Windows Server 2008 SP2, and the Azure guest operating
* system that is substantially compatible with Windows Server 2008 R2.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx
* for more information)/*from  w  ww  .jav a  2 s .com*/
*
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The List Operating System Families operation response.
*/
@Override
public OperatingSystemListFamiliesResponse listFamilies()
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        CloudTracing.enter(invocationId, this, "listFamiliesAsync", 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 + "/operatingsystemfamilies";
    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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2015-04-01");

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element operatingSystemFamiliesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamilies");
            if (operatingSystemFamiliesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(operatingSystemFamiliesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element operatingSystemFamiliesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(operatingSystemFamiliesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily")
                            .get(i1));
                    OperatingSystemListFamiliesResponse.OperatingSystemFamily operatingSystemFamilyInstance = new OperatingSystemListFamiliesResponse.OperatingSystemFamily();
                    result.getOperatingSystemFamilies().add(operatingSystemFamilyInstance);

                    Element nameElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        int nameInstance;
                        nameInstance = DatatypeConverter.parseInt(nameElement.getTextContent());
                        operatingSystemFamilyInstance.setName(nameInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent() != null
                                ? new String(Base64.decode(labelElement.getTextContent()))
                                : null;
                        operatingSystemFamilyInstance.setLabel(labelInstance);
                    }

                    Element operatingSystemsSequenceElement = XmlUtility.getElementByTagNameNS(
                            operatingSystemFamiliesElement, "http://schemas.microsoft.com/windowsazure",
                            "OperatingSystems");
                    if (operatingSystemsSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element operatingSystemsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                                    .get(i2));
                            OperatingSystemListFamiliesResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListFamiliesResponse.OperatingSystem();
                            operatingSystemFamilyInstance.getOperatingSystems().add(operatingSystemInstance);

                            Element versionElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Version");
                            if (versionElement != null) {
                                String versionInstance;
                                versionInstance = versionElement.getTextContent();
                                operatingSystemInstance.setVersion(versionInstance);
                            }

                            Element labelElement2 = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Label");
                            if (labelElement2 != null) {
                                String labelInstance2;
                                labelInstance2 = labelElement2.getTextContent() != null
                                        ? new String(Base64.decode(labelElement2.getTextContent()))
                                        : null;
                                operatingSystemInstance.setLabel(labelInstance2);
                            }

                            Element isDefaultElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "IsDefault");
                            if (isDefaultElement != null) {
                                boolean isDefaultInstance;
                                isDefaultInstance = DatatypeConverter
                                        .parseBoolean(isDefaultElement.getTextContent().toLowerCase());
                                operatingSystemInstance.setIsDefault(isDefaultInstance);
                            }

                            Element isActiveElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "IsActive");
                            if (isActiveElement != null) {
                                boolean isActiveInstance;
                                isActiveInstance = DatatypeConverter
                                        .parseBoolean(isActiveElement.getTextContent().toLowerCase());
                                operatingSystemInstance.setIsActive(isActiveInstance);
                            }
                        }
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.sql.ServiceObjectiveOperationsImpl.java

/**
* Returns information about all Service Objectives on an Azure SQL Database
* Server./*from   www .  j a v a2 s . co  m*/
*
* @param serverName Required. The name of the Azure SQL Database Server to
* be queried.
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return Response containing the list of service objective for a given
* server.  This is returnedfrom a call to List Service Objectives.
*/
@Override
public ServiceObjectiveListResponse list(String serverName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }

    // 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);
        CloudTracing.enter(invocationId, this, "listAsync", tracingParameters);
    }

    // Construct URL
    String 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");
    url = url + "/serviceobjectives";
    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
    HttpGet httpRequest = new HttpGet(url);

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

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResources");
            if (serviceResourcesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                            .get(i1));
                    ServiceObjective serviceResourceInstance = new ServiceObjective();
                    result.getServiceObjectives().add(serviceResourceInstance);

                    Element idElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Id");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        serviceResourceInstance.setId(idInstance);
                    }

                    Element isDefaultElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "IsDefault");
                    if (isDefaultElement != null) {
                        boolean isDefaultInstance;
                        isDefaultInstance = DatatypeConverter
                                .parseBoolean(isDefaultElement.getTextContent().toLowerCase());
                        serviceResourceInstance.setIsDefault(isDefaultInstance);
                    }

                    Element isSystemElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "IsSystem");
                    if (isSystemElement != null) {
                        boolean isSystemInstance;
                        isSystemInstance = DatatypeConverter
                                .parseBoolean(isSystemElement.getTextContent().toLowerCase());
                        serviceResourceInstance.setIsSystem(isSystemInstance);
                    }

                    Element descriptionElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Description");
                    if (descriptionElement != null) {
                        String descriptionInstance;
                        descriptionInstance = descriptionElement.getTextContent();
                        serviceResourceInstance.setDescription(descriptionInstance);
                    }

                    Element enabledElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Enabled");
                    if (enabledElement != null) {
                        boolean enabledInstance;
                        enabledInstance = DatatypeConverter
                                .parseBoolean(enabledElement.getTextContent().toLowerCase());
                        serviceResourceInstance.setEnabled(enabledInstance);
                    }

                    Element dimensionSettingsSequenceElement = XmlUtility.getElementByTagNameNS(
                            serviceResourcesElement, "http://schemas.microsoft.com/windowsazure",
                            "DimensionSettings");
                    if (dimensionSettingsSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(dimensionSettingsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element dimensionSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(dimensionSettingsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                                    .get(i2));
                            ServiceObjective.DimensionSettingResponse serviceResourceInstance2 = new ServiceObjective.DimensionSettingResponse();
                            serviceResourceInstance.getDimensionSettings().add(serviceResourceInstance2);

                            Element idElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Id");
                            if (idElement2 != null) {
                                String idInstance2;
                                idInstance2 = idElement2.getTextContent();
                                serviceResourceInstance2.setId(idInstance2);
                            }

                            Element descriptionElement2 = XmlUtility.getElementByTagNameNS(
                                    dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure",
                                    "Description");
                            if (descriptionElement2 != null) {
                                String descriptionInstance2;
                                descriptionInstance2 = descriptionElement2.getTextContent();
                                serviceResourceInstance2.setDescription(descriptionInstance2);
                            }

                            Element ordinalElement = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Ordinal");
                            if (ordinalElement != null) {
                                byte ordinalInstance;
                                ordinalInstance = DatatypeConverter.parseByte(ordinalElement.getTextContent());
                                serviceResourceInstance2.setOrdinal(ordinalInstance);
                            }

                            Element isDefaultElement2 = XmlUtility.getElementByTagNameNS(
                                    dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure",
                                    "IsDefault");
                            if (isDefaultElement2 != null) {
                                boolean isDefaultInstance2;
                                isDefaultInstance2 = DatatypeConverter
                                        .parseBoolean(isDefaultElement2.getTextContent().toLowerCase());
                                serviceResourceInstance2.setIsDefault(isDefaultInstance2);
                            }

                            Element nameElement = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Name");
                            if (nameElement != null) {
                                String nameInstance;
                                nameInstance = nameElement.getTextContent();
                                serviceResourceInstance2.setName(nameInstance);
                            }

                            Element typeElement = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Type");
                            if (typeElement != null) {
                                String typeInstance;
                                typeInstance = typeElement.getTextContent();
                                serviceResourceInstance2.setType(typeInstance);
                            }

                            Element stateElement = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                    "http://schemas.microsoft.com/windowsazure", "State");
                            if (stateElement != null) {
                                String stateInstance;
                                stateInstance = stateElement.getTextContent();
                                serviceResourceInstance2.setState(stateInstance);
                            }
                        }
                    }

                    Element nameElement2 = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement2 != null) {
                        String nameInstance2;
                        nameInstance2 = nameElement2.getTextContent();
                        serviceResourceInstance.setName(nameInstance2);
                    }

                    Element typeElement2 = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Type");
                    if (typeElement2 != null) {
                        String typeInstance2;
                        typeInstance2 = typeElement2.getTextContent();
                        serviceResourceInstance.setType(typeInstance2);
                    }

                    Element stateElement2 = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "State");
                    if (stateElement2 != null) {
                        String stateInstance2;
                        stateInstance2 = stateElement2.getTextContent();
                        serviceResourceInstance.setState(stateInstance2);
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.servicebus.NamespaceOperationsImpl.java

/**
* Creates a new service namespace. Once created, this namespace's resource
* manifest is immutable. This operation is idempotent.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for
* more information)//from  www. j av  a 2 s. co m
*
* @param namespaceName Required. The namespace name.
* @param region Optional. The namespace region.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The response to a request for a particular namespace.
*/
@Override
public ServiceBusNamespaceResponse create(String namespaceName, String region)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }

    // 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("namespaceName", namespaceName);
        tracingParameters.put("region", region);
        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/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    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
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Accept", "application/atom+xml");
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-07-01");

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

    Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
    requestDoc.appendChild(entryElement);

    Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
    entryElement.appendChild(contentElement);

    Attr typeAttribute = requestDoc.createAttribute("type");
    typeAttribute.setValue("application/xml");
    contentElement.setAttributeNode(typeAttribute);

    Element namespaceDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceDescription");
    contentElement.appendChild(namespaceDescriptionElement);

    if (region != null) {
        Element regionElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Region");
        regionElement.appendChild(requestDoc.createTextNode(region));
        namespaceDescriptionElement.appendChild(regionElement);
    }

    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/atom+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
        ServiceBusNamespaceResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusNamespaceResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element namespaceDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "NamespaceDescription");
                    if (namespaceDescriptionElement2 != null) {
                        ServiceBusNamespace namespaceDescriptionInstance = new ServiceBusNamespace();
                        result.setNamespace(namespaceDescriptionInstance);

                        Element nameElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Name");
                        if (nameElement != null) {
                            String nameInstance;
                            nameInstance = nameElement.getTextContent();
                            namespaceDescriptionInstance.setName(nameInstance);
                        }

                        Element regionElement2 = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Region");
                        if (regionElement2 != null) {
                            String regionInstance;
                            regionInstance = regionElement2.getTextContent();
                            namespaceDescriptionInstance.setRegion(regionInstance);
                        }

                        Element statusElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Status");
                        if (statusElement != null) {
                            String statusInstance;
                            statusInstance = statusElement.getTextContent();
                            namespaceDescriptionInstance.setStatus(statusInstance);
                        }

                        Element createdAtElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedAt");
                        if (createdAtElement != null) {
                            Calendar createdAtInstance;
                            createdAtInstance = DatatypeConverter
                                    .parseDateTime(createdAtElement.getTextContent());
                            namespaceDescriptionInstance.setCreatedAt(createdAtInstance);
                        }

                        Element acsManagementEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AcsManagementEndpoint");
                        if (acsManagementEndpointElement != null) {
                            URI acsManagementEndpointInstance;
                            acsManagementEndpointInstance = new URI(
                                    acsManagementEndpointElement.getTextContent());
                            namespaceDescriptionInstance
                                    .setAcsManagementEndpoint(acsManagementEndpointInstance);
                        }

                        Element serviceBusEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ServiceBusEndpoint");
                        if (serviceBusEndpointElement != null) {
                            URI serviceBusEndpointInstance;
                            serviceBusEndpointInstance = new URI(serviceBusEndpointElement.getTextContent());
                            namespaceDescriptionInstance.setServiceBusEndpoint(serviceBusEndpointInstance);
                        }

                        Element subscriptionIdElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionId");
                        if (subscriptionIdElement != null) {
                            String subscriptionIdInstance;
                            subscriptionIdInstance = subscriptionIdElement.getTextContent();
                            namespaceDescriptionInstance.setSubscriptionId(subscriptionIdInstance);
                        }

                        Element enabledElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Enabled");
                        if (enabledElement != null) {
                            boolean enabledInstance;
                            enabledInstance = DatatypeConverter
                                    .parseBoolean(enabledElement.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setEnabled(enabledInstance);
                        }

                        Element createACSNamespaceElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreateACSNamespace");
                        if (createACSNamespaceElement != null) {
                            boolean createACSNamespaceInstance;
                            createACSNamespaceInstance = DatatypeConverter
                                    .parseBoolean(createACSNamespaceElement.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setCreateACSNamespace(createACSNamespaceInstance);
                        }

                        Element namespaceTypeElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "NamespaceType");
                        if (namespaceTypeElement != null && namespaceTypeElement.getTextContent() != null
                                && !namespaceTypeElement.getTextContent().isEmpty()) {
                            NamespaceType namespaceTypeInstance;
                            namespaceTypeInstance = NamespaceType
                                    .valueOf(namespaceTypeElement.getTextContent());
                            namespaceDescriptionInstance.setNamespaceType(namespaceTypeInstance);
                        }
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.SubscriptionOperationsImpl.java

/**
* The List Subscription Operations operation returns a list of create,
* update, and delete operations that were performed on a subscription
* during the specified timeframe.  (see//from   w ww .  ja v a  2 s  .c  o m
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the List Subscription
* Operations operation.
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The List Subscription Operations operation response.
*/
@Override
public SubscriptionListOperationsResponse listOperations(SubscriptionListOperationsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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, "listOperationsAsync", 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 + "/operations";
    ArrayList<String> queryParameters = new ArrayList<String>();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    queryParameters.add("StartTime="
            + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"));
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
    queryParameters.add("EndTime="
            + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
    if (parameters.getObjectIdFilter() != null) {
        queryParameters.add("ObjectIdFilter=" + URLEncoder.encode(parameters.getObjectIdFilter(), "UTF-8"));
    }
    if (parameters.getOperationStatus() != null) {
        queryParameters.add("OperationResultFilter="
                + URLEncoder.encode(parameters.getOperationStatus().toString(), "UTF-8"));
    }
    if (parameters.getContinuationToken() != null) {
        queryParameters
                .add("ContinuationToken=" + URLEncoder.encode(parameters.getContinuationToken(), "UTF-8"));
    }
    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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2014-10-01");

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element subscriptionOperationCollectionElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "SubscriptionOperationCollection");
            if (subscriptionOperationCollectionElement != null) {
                Element continuationTokenElement = XmlUtility.getElementByTagNameNS(
                        subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure",
                        "ContinuationToken");
                if (continuationTokenElement != null) {
                    String continuationTokenInstance;
                    continuationTokenInstance = continuationTokenElement.getTextContent();
                    result.setContinuationToken(continuationTokenInstance);
                }

                Element subscriptionOperationsSequenceElement = XmlUtility.getElementByTagNameNS(
                        subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure",
                        "SubscriptionOperations");
                if (subscriptionOperationsSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(subscriptionOperationsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element subscriptionOperationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(subscriptionOperationsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation")
                                .get(i1));
                        SubscriptionListOperationsResponse.SubscriptionOperation subscriptionOperationInstance = new SubscriptionListOperationsResponse.SubscriptionOperation();
                        result.getSubscriptionOperations().add(subscriptionOperationInstance);

                        Element operationIdElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationId");
                        if (operationIdElement != null) {
                            String operationIdInstance;
                            operationIdInstance = operationIdElement.getTextContent();
                            subscriptionOperationInstance.setOperationId(operationIdInstance);
                        }

                        Element operationObjectIdElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationObjectId");
                        if (operationObjectIdElement != null) {
                            String operationObjectIdInstance;
                            operationObjectIdInstance = operationObjectIdElement.getTextContent();
                            subscriptionOperationInstance.setOperationObjectId(operationObjectIdInstance);
                        }

                        Element operationNameElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationName");
                        if (operationNameElement != null) {
                            String operationNameInstance;
                            operationNameInstance = operationNameElement.getTextContent();
                            subscriptionOperationInstance.setOperationName(operationNameInstance);
                        }

                        Element operationParametersSequenceElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationParameters");
                        if (operationParametersSequenceElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(operationParametersSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "OperationParameter")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element operationParametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(operationParametersSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure",
                                                "OperationParameter")
                                        .get(i2));
                                String operationParametersKey = XmlUtility.getElementByTagNameNS(
                                        operationParametersElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement",
                                        "Name").getTextContent();
                                String operationParametersValue = XmlUtility.getElementByTagNameNS(
                                        operationParametersElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement",
                                        "Value").getTextContent();
                                subscriptionOperationInstance.getOperationParameters()
                                        .put(operationParametersKey, operationParametersValue);
                            }
                        }

                        Element operationCallerElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationCaller");
                        if (operationCallerElement != null) {
                            SubscriptionListOperationsResponse.OperationCallerDetails operationCallerInstance = new SubscriptionListOperationsResponse.OperationCallerDetails();
                            subscriptionOperationInstance.setOperationCaller(operationCallerInstance);

                            Element usedServiceManagementApiElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "UsedServiceManagementApi");
                            if (usedServiceManagementApiElement != null) {
                                boolean usedServiceManagementApiInstance;
                                usedServiceManagementApiInstance = DatatypeConverter.parseBoolean(
                                        usedServiceManagementApiElement.getTextContent().toLowerCase());
                                operationCallerInstance
                                        .setUsedServiceManagementApi(usedServiceManagementApiInstance);
                            }

                            Element userEmailAddressElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "UserEmailAddress");
                            if (userEmailAddressElement != null) {
                                String userEmailAddressInstance;
                                userEmailAddressInstance = userEmailAddressElement.getTextContent();
                                operationCallerInstance.setUserEmailAddress(userEmailAddressInstance);
                            }

                            Element subscriptionCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "SubscriptionCertificateThumbprint");
                            if (subscriptionCertificateThumbprintElement != null) {
                                String subscriptionCertificateThumbprintInstance;
                                subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement
                                        .getTextContent();
                                operationCallerInstance.setSubscriptionCertificateThumbprint(
                                        subscriptionCertificateThumbprintInstance);
                            }

                            Element clientIPElement = XmlUtility.getElementByTagNameNS(operationCallerElement,
                                    "http://schemas.microsoft.com/windowsazure", "ClientIP");
                            if (clientIPElement != null) {
                                InetAddress clientIPInstance;
                                clientIPInstance = InetAddress.getByName(clientIPElement.getTextContent());
                                operationCallerInstance.setClientIPAddress(clientIPInstance);
                            }
                        }

                        Element operationStatusElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationStatus");
                        if (operationStatusElement != null) {
                            String operationStatusInstance;
                            operationStatusInstance = operationStatusElement.getTextContent();
                            subscriptionOperationInstance.setOperationStatus(operationStatusInstance);
                        }

                        Element operationStartedTimeElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationStartedTime");
                        if (operationStartedTimeElement != null) {
                            Calendar operationStartedTimeInstance;
                            operationStartedTimeInstance = DatatypeConverter
                                    .parseDateTime(operationStartedTimeElement.getTextContent());
                            subscriptionOperationInstance.setOperationStartedTime(operationStartedTimeInstance);
                        }

                        Element operationCompletedTimeElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationCompletedTime");
                        if (operationCompletedTimeElement != null) {
                            Calendar operationCompletedTimeInstance;
                            operationCompletedTimeInstance = DatatypeConverter
                                    .parseDateTime(operationCompletedTimeElement.getTextContent());
                            subscriptionOperationInstance
                                    .setOperationCompletedTime(operationCompletedTimeInstance);
                        }
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.servicebus.QueueOperationsImpl.java

/**
* Creates a new queue. Once created, this queue's resource manifest is
* immutable. This operation is idempotent. Repeating the create call,
* after a queue with same name has been created successfully, will result
* in a 409 Conflict error message.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856295.aspx for
* more information)//  w w w. ja v a  2  s.c o m
*
* @param namespaceName Required. The namespace name.
* @param queue Required. The service bus queue.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return A response to a request for a particular queue.
*/
@Override
public ServiceBusQueueResponse create(String namespaceName, ServiceBusQueueCreateParameters queue)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (queue == null) {
        throw new NullPointerException("queue");
    }
    if (queue.getName() == null) {
        throw new NullPointerException("queue.Name");
    }

    // 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("namespaceName", namespaceName);
        tracingParameters.put("queue", queue);
        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/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/queues/";
    url = url + URLEncoder.encode(queue.getName(), "UTF-8");
    url = url + "/";
    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
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-08-01");
    httpRequest.setHeader("x-process-at", "ServiceBus");

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

    Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
    requestDoc.appendChild(entryElement);

    Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
    entryElement.appendChild(contentElement);

    Attr typeAttribute = requestDoc.createAttribute("type");
    typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8");
    contentElement.setAttributeNode(typeAttribute);

    Element queueDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "QueueDescription");
    contentElement.appendChild(queueDescriptionElement);

    if (queue.getLockDuration() != null) {
        Element lockDurationElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "LockDuration");
        lockDurationElement.appendChild(requestDoc.createTextNode(queue.getLockDuration()));
        queueDescriptionElement.appendChild(lockDurationElement);
    }

    Element maxSizeInMegabytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes");
    maxSizeInMegabytesElement
            .appendChild(requestDoc.createTextNode(Integer.toString(queue.getMaxSizeInMegabytes())));
    queueDescriptionElement.appendChild(maxSizeInMegabytesElement);

    Element requiresDuplicateDetectionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "RequiresDuplicateDetection");
    requiresDuplicateDetectionElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(queue.isRequiresDuplicateDetection()).toLowerCase()));
    queueDescriptionElement.appendChild(requiresDuplicateDetectionElement);

    Element requiresSessionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RequiresSession");
    requiresSessionElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(queue.isRequiresSession()).toLowerCase()));
    queueDescriptionElement.appendChild(requiresSessionElement);

    if (queue.getDefaultMessageTimeToLive() != null) {
        Element defaultMessageTimeToLiveElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DefaultMessageTimeToLive");
        defaultMessageTimeToLiveElement
                .appendChild(requestDoc.createTextNode(queue.getDefaultMessageTimeToLive()));
        queueDescriptionElement.appendChild(defaultMessageTimeToLiveElement);
    }

    Element deadLetteringOnMessageExpirationElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "DeadLetteringOnMessageExpiration");
    deadLetteringOnMessageExpirationElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(queue.isDeadLetteringOnMessageExpiration()).toLowerCase()));
    queueDescriptionElement.appendChild(deadLetteringOnMessageExpirationElement);

    if (queue.getDuplicateDetectionHistoryTimeWindow() != null) {
        Element duplicateDetectionHistoryTimeWindowElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DuplicateDetectionHistoryTimeWindow");
        duplicateDetectionHistoryTimeWindowElement
                .appendChild(requestDoc.createTextNode(queue.getDuplicateDetectionHistoryTimeWindow()));
        queueDescriptionElement.appendChild(duplicateDetectionHistoryTimeWindowElement);
    }

    Element enableBatchedOperationsElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations");
    enableBatchedOperationsElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(queue.isEnableBatchedOperations()).toLowerCase()));
    queueDescriptionElement.appendChild(enableBatchedOperationsElement);

    Element sizeInBytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes");
    sizeInBytesElement.appendChild(requestDoc.createTextNode(Integer.toString(queue.getSizeInBytes())));
    queueDescriptionElement.appendChild(sizeInBytesElement);

    Element messageCountElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MessageCount");
    messageCountElement.appendChild(requestDoc.createTextNode(Integer.toString(queue.getMessageCount())));
    queueDescriptionElement.appendChild(messageCountElement);

    Element isAnonymousAccessibleElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible");
    isAnonymousAccessibleElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(queue.isAnonymousAccessible()).toLowerCase()));
    queueDescriptionElement.appendChild(isAnonymousAccessibleElement);

    if (queue.getAuthorizationRules() != null) {
        if (queue.getAuthorizationRules() instanceof LazyCollection == false
                || ((LazyCollection) queue.getAuthorizationRules()).isInitialized()) {
            Element authorizationRulesSequenceElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                    "AuthorizationRules");
            for (ServiceBusSharedAccessAuthorizationRule authorizationRulesItem : queue
                    .getAuthorizationRules()) {
                Element authorizationRuleElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                        "AuthorizationRule");
                authorizationRulesSequenceElement.appendChild(authorizationRuleElement);

                Attr typeAttribute2 = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                        "type");
                typeAttribute2.setValue("SharedAccessAuthorizationRule");
                authorizationRuleElement.setAttributeNode(typeAttribute2);

                if (authorizationRulesItem.getClaimType() != null) {
                    Element claimTypeElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType");
                    claimTypeElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimType()));
                    authorizationRuleElement.appendChild(claimTypeElement);
                }

                if (authorizationRulesItem.getClaimValue() != null) {
                    Element claimValueElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "ClaimValue");
                    claimValueElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimValue()));
                    authorizationRuleElement.appendChild(claimValueElement);
                }

                if (authorizationRulesItem.getRights() != null) {
                    if (authorizationRulesItem.getRights() instanceof LazyCollection == false
                            || ((LazyCollection) authorizationRulesItem.getRights()).isInitialized()) {
                        Element rightsSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        for (AccessRight rightsItem : authorizationRulesItem.getRights()) {
                            Element rightsItemElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                    "AccessRights");
                            rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                            rightsSequenceElement.appendChild(rightsItemElement);
                        }
                        authorizationRuleElement.appendChild(rightsSequenceElement);
                    }
                }

                Element createdTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                createdTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime())));
                authorizationRuleElement.appendChild(createdTimeElement);

                if (authorizationRulesItem.getKeyName() != null) {
                    Element keyNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName");
                    keyNameElement.appendChild(requestDoc.createTextNode(authorizationRulesItem.getKeyName()));
                    authorizationRuleElement.appendChild(keyNameElement);
                }

                Element modifiedTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
                modifiedTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime())));
                authorizationRuleElement.appendChild(modifiedTimeElement);

                if (authorizationRulesItem.getPrimaryKey() != null) {
                    Element primaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "PrimaryKey");
                    primaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getPrimaryKey()));
                    authorizationRuleElement.appendChild(primaryKeyElement);
                }

                if (authorizationRulesItem.getSecondaryKey() != null) {
                    Element secondaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SecondaryKey");
                    secondaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getSecondaryKey()));
                    authorizationRuleElement.appendChild(secondaryKeyElement);
                }
            }
            queueDescriptionElement.appendChild(authorizationRulesSequenceElement);
        }
    }

    if (queue.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status");
        statusElement.appendChild(requestDoc.createTextNode(queue.getStatus()));
        queueDescriptionElement.appendChild(statusElement);
    }

    Element supportOrderingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering");
    supportOrderingElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(queue.isSupportOrdering()).toLowerCase()));
    queueDescriptionElement.appendChild(supportOrderingElement);

    if (queue.getCountDetails() != null) {
        Element countDetailsElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails");
        queueDescriptionElement.appendChild(countDetailsElement);

        Element activeMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount");
        activeMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(queue.getCountDetails().getActiveMessageCount())));
        countDetailsElement.appendChild(activeMessageCountElement);

        Element deadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount");
        deadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(queue.getCountDetails().getDeadLetterMessageCount())));
        countDetailsElement.appendChild(deadLetterMessageCountElement);

        Element scheduledMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount");
        scheduledMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(queue.getCountDetails().getScheduledMessageCount())));
        countDetailsElement.appendChild(scheduledMessageCountElement);

        Element transferDeadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                "TransferDeadLetterMessageCount");
        transferDeadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(queue.getCountDetails().getTransferDeadLetterMessageCount())));
        countDetailsElement.appendChild(transferDeadLetterMessageCountElement);

        Element transferMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount");
        transferMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(queue.getCountDetails().getTransferMessageCount())));
        countDetailsElement.appendChild(transferMessageCountElement);
    }

    if (queue.getAutoDeleteOnIdle() != null) {
        Element autoDeleteOnIdleElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle");
        autoDeleteOnIdleElement.appendChild(requestDoc.createTextNode(queue.getAutoDeleteOnIdle()));
        queueDescriptionElement.appendChild(autoDeleteOnIdleElement);
    }

    if (queue.getEntityAvailabilityStatus() != null) {
        Element entityAvailabilityStatusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "EntityAvailabilityStatus");
        entityAvailabilityStatusElement
                .appendChild(requestDoc.createTextNode(queue.getEntityAvailabilityStatus()));
        queueDescriptionElement.appendChild(entityAvailabilityStatusElement);
    }

    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/atom+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
        ServiceBusQueueResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusQueueResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element titleElement = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "title");
                if (titleElement != null) {
                }

                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element queueDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "QueueDescription");
                    if (queueDescriptionElement2 != null) {
                        ServiceBusQueue queueDescriptionInstance = new ServiceBusQueue();
                        result.setQueue(queueDescriptionInstance);

                        Element lockDurationElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "LockDuration");
                        if (lockDurationElement2 != null) {
                            String lockDurationInstance;
                            lockDurationInstance = lockDurationElement2.getTextContent();
                            queueDescriptionInstance.setLockDuration(lockDurationInstance);
                        }

                        Element maxSizeInMegabytesElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxSizeInMegabytes");
                        if (maxSizeInMegabytesElement2 != null) {
                            int maxSizeInMegabytesInstance;
                            maxSizeInMegabytesInstance = DatatypeConverter
                                    .parseInt(maxSizeInMegabytesElement2.getTextContent());
                            queueDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance);
                        }

                        Element requiresDuplicateDetectionElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresDuplicateDetection");
                        if (requiresDuplicateDetectionElement2 != null) {
                            boolean requiresDuplicateDetectionInstance;
                            requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean(
                                    requiresDuplicateDetectionElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance
                                    .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance);
                        }

                        Element requiresSessionElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresSession");
                        if (requiresSessionElement2 != null) {
                            boolean requiresSessionInstance;
                            requiresSessionInstance = DatatypeConverter
                                    .parseBoolean(requiresSessionElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setRequiresSession(requiresSessionInstance);
                        }

                        Element defaultMessageTimeToLiveElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DefaultMessageTimeToLive");
                        if (defaultMessageTimeToLiveElement2 != null) {
                            String defaultMessageTimeToLiveInstance;
                            defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement2
                                    .getTextContent();
                            queueDescriptionInstance
                                    .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance);
                        }

                        Element deadLetteringOnMessageExpirationElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DeadLetteringOnMessageExpiration");
                        if (deadLetteringOnMessageExpirationElement2 != null) {
                            boolean deadLetteringOnMessageExpirationInstance;
                            deadLetteringOnMessageExpirationInstance = DatatypeConverter.parseBoolean(
                                    deadLetteringOnMessageExpirationElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setDeadLetteringOnMessageExpiration(
                                    deadLetteringOnMessageExpirationInstance);
                        }

                        Element duplicateDetectionHistoryTimeWindowElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DuplicateDetectionHistoryTimeWindow");
                        if (duplicateDetectionHistoryTimeWindowElement2 != null) {
                            String duplicateDetectionHistoryTimeWindowInstance;
                            duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement2
                                    .getTextContent();
                            queueDescriptionInstance.setDuplicateDetectionHistoryTimeWindow(
                                    duplicateDetectionHistoryTimeWindowInstance);
                        }

                        Element maxDeliveryCountElement = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxDeliveryCount");
                        if (maxDeliveryCountElement != null) {
                            int maxDeliveryCountInstance;
                            maxDeliveryCountInstance = DatatypeConverter
                                    .parseInt(maxDeliveryCountElement.getTextContent());
                            queueDescriptionInstance.setMaxDeliveryCount(maxDeliveryCountInstance);
                        }

                        Element enableBatchedOperationsElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EnableBatchedOperations");
                        if (enableBatchedOperationsElement2 != null) {
                            boolean enableBatchedOperationsInstance;
                            enableBatchedOperationsInstance = DatatypeConverter.parseBoolean(
                                    enableBatchedOperationsElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance
                                    .setEnableBatchedOperations(enableBatchedOperationsInstance);
                        }

                        Element sizeInBytesElement2 = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SizeInBytes");
                        if (sizeInBytesElement2 != null) {
                            int sizeInBytesInstance;
                            sizeInBytesInstance = DatatypeConverter
                                    .parseInt(sizeInBytesElement2.getTextContent());
                            queueDescriptionInstance.setSizeInBytes(sizeInBytesInstance);
                        }

                        Element messageCountElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MessageCount");
                        if (messageCountElement2 != null) {
                            int messageCountInstance;
                            messageCountInstance = DatatypeConverter
                                    .parseInt(messageCountElement2.getTextContent());
                            queueDescriptionInstance.setMessageCount(messageCountInstance);
                        }

                        Element isAnonymousAccessibleElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "IsAnonymousAccessible");
                        if (isAnonymousAccessibleElement2 != null) {
                            boolean isAnonymousAccessibleInstance;
                            isAnonymousAccessibleInstance = DatatypeConverter
                                    .parseBoolean(isAnonymousAccessibleElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance);
                        }

                        Element authorizationRulesSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AuthorizationRules");
                        if (authorizationRulesSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AuthorizationRule")
                                    .size(); i1 = i1 + 1) {
                                org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                "AuthorizationRule")
                                        .get(i1));
                                ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                                queueDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance);

                                Element claimTypeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimType");
                                if (claimTypeElement2 != null) {
                                    String claimTypeInstance;
                                    claimTypeInstance = claimTypeElement2.getTextContent();
                                    authorizationRuleInstance.setClaimType(claimTypeInstance);
                                }

                                Element claimValueElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimValue");
                                if (claimValueElement2 != null) {
                                    String claimValueInstance;
                                    claimValueInstance = claimValueElement2.getTextContent();
                                    authorizationRuleInstance.setClaimValue(claimValueInstance);
                                }

                                Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "Rights");
                                if (rightsSequenceElement2 != null) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(rightsSequenceElement2,
                                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                    "AccessRights")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(rightsSequenceElement2,
                                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                        "AccessRights")
                                                .get(i2));
                                        authorizationRuleInstance.getRights()
                                                .add(AccessRight.valueOf(rightsElement.getTextContent()));
                                    }
                                }

                                Element createdTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "CreatedTime");
                                if (createdTimeElement2 != null) {
                                    Calendar createdTimeInstance;
                                    createdTimeInstance = DatatypeConverter
                                            .parseDateTime(createdTimeElement2.getTextContent());
                                    authorizationRuleInstance.setCreatedTime(createdTimeInstance);
                                }

                                Element keyNameElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "KeyName");
                                if (keyNameElement2 != null) {
                                    String keyNameInstance;
                                    keyNameInstance = keyNameElement2.getTextContent();
                                    authorizationRuleInstance.setKeyName(keyNameInstance);
                                }

                                Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ModifiedTime");
                                if (modifiedTimeElement2 != null) {
                                    Calendar modifiedTimeInstance;
                                    modifiedTimeInstance = DatatypeConverter
                                            .parseDateTime(modifiedTimeElement2.getTextContent());
                                    authorizationRuleInstance.setModifiedTime(modifiedTimeInstance);
                                }

                                Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "PrimaryKey");
                                if (primaryKeyElement2 != null) {
                                    String primaryKeyInstance;
                                    primaryKeyInstance = primaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setPrimaryKey(primaryKeyInstance);
                                }

                                Element secondaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "SecondaryKey");
                                if (secondaryKeyElement2 != null) {
                                    String secondaryKeyInstance;
                                    secondaryKeyInstance = secondaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance);
                                }
                            }
                        }

                        Element statusElement2 = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Status");
                        if (statusElement2 != null) {
                            String statusInstance;
                            statusInstance = statusElement2.getTextContent();
                            queueDescriptionInstance.setStatus(statusInstance);
                        }

                        Element createdAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedAt");
                        if (createdAtElement != null) {
                            Calendar createdAtInstance;
                            createdAtInstance = DatatypeConverter
                                    .parseDateTime(createdAtElement.getTextContent());
                            queueDescriptionInstance.setCreatedAt(createdAtInstance);
                        }

                        Element updatedAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "UpdatedAt");
                        if (updatedAtElement != null) {
                            Calendar updatedAtInstance;
                            updatedAtInstance = DatatypeConverter
                                    .parseDateTime(updatedAtElement.getTextContent());
                            queueDescriptionInstance.setUpdatedAt(updatedAtInstance);
                        }

                        Element accessedAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AccessedAt");
                        if (accessedAtElement != null) {
                            Calendar accessedAtInstance;
                            accessedAtInstance = DatatypeConverter
                                    .parseDateTime(accessedAtElement.getTextContent());
                            queueDescriptionInstance.setAccessedAt(accessedAtInstance);
                        }

                        Element supportOrderingElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SupportOrdering");
                        if (supportOrderingElement2 != null) {
                            boolean supportOrderingInstance;
                            supportOrderingInstance = DatatypeConverter
                                    .parseBoolean(supportOrderingElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setSupportOrdering(supportOrderingInstance);
                        }

                        Element countDetailsElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CountDetails");
                        if (countDetailsElement2 != null) {
                            CountDetails countDetailsInstance = new CountDetails();
                            queueDescriptionInstance.setCountDetails(countDetailsInstance);

                            Element activeMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "ActiveMessageCount");
                            if (activeMessageCountElement2 != null) {
                                int activeMessageCountInstance;
                                activeMessageCountInstance = DatatypeConverter
                                        .parseInt(activeMessageCountElement2.getTextContent());
                                countDetailsInstance.setActiveMessageCount(activeMessageCountInstance);
                            }

                            Element deadLetterMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "DeadLetterMessageCount");
                            if (deadLetterMessageCountElement2 != null) {
                                int deadLetterMessageCountInstance;
                                deadLetterMessageCountInstance = DatatypeConverter
                                        .parseInt(deadLetterMessageCountElement2.getTextContent());
                                countDetailsInstance.setDeadLetterMessageCount(deadLetterMessageCountInstance);
                            }

                            Element scheduledMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "ScheduledMessageCount");
                            if (scheduledMessageCountElement2 != null) {
                                int scheduledMessageCountInstance;
                                scheduledMessageCountInstance = DatatypeConverter
                                        .parseInt(scheduledMessageCountElement2.getTextContent());
                                countDetailsInstance.setScheduledMessageCount(scheduledMessageCountInstance);
                            }

                            Element transferDeadLetterMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "TransferDeadLetterMessageCount");
                            if (transferDeadLetterMessageCountElement2 != null) {
                                int transferDeadLetterMessageCountInstance;
                                transferDeadLetterMessageCountInstance = DatatypeConverter
                                        .parseInt(transferDeadLetterMessageCountElement2.getTextContent());
                                countDetailsInstance.setTransferDeadLetterMessageCount(
                                        transferDeadLetterMessageCountInstance);
                            }

                            Element transferMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "TransferMessageCount");
                            if (transferMessageCountElement2 != null) {
                                int transferMessageCountInstance;
                                transferMessageCountInstance = DatatypeConverter
                                        .parseInt(transferMessageCountElement2.getTextContent());
                                countDetailsInstance.setTransferMessageCount(transferMessageCountInstance);
                            }
                        }

                        Element autoDeleteOnIdleElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AutoDeleteOnIdle");
                        if (autoDeleteOnIdleElement2 != null) {
                            String autoDeleteOnIdleInstance;
                            autoDeleteOnIdleInstance = autoDeleteOnIdleElement2.getTextContent();
                            queueDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance);
                        }

                        Element entityAvailabilityStatusElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EntityAvailabilityStatus");
                        if (entityAvailabilityStatusElement2 != null) {
                            String entityAvailabilityStatusInstance;
                            entityAvailabilityStatusInstance = entityAvailabilityStatusElement2
                                    .getTextContent();
                            queueDescriptionInstance
                                    .setEntityAvailabilityStatus(entityAvailabilityStatusInstance);
                        }
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.servicebus.TopicOperationsImpl.java

/**
* Creates a new topic. Once created, this topic resource manifest is
* immutable. This operation is not idempotent. Repeating the create call,
* after a topic with same name has been created successfully, will result
* in a 409 Conflict error message.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/hh780728.aspx for
* more information)//from w ww .j  a  v a 2  s  . c o  m
*
* @param namespaceName Required. The namespace name.
* @param topic Required. The Service Bus topic.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return A response to a request for a particular topic.
*/
@Override
public ServiceBusTopicResponse create(String namespaceName, ServiceBusTopic topic)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (topic == null) {
        throw new NullPointerException("topic");
    }

    // 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("namespaceName", namespaceName);
        tracingParameters.put("topic", topic);
        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/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/topics/";
    if (topic.getName() != null) {
        url = url + URLEncoder.encode(topic.getName(), "UTF-8");
    }
    url = url + "/";
    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
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-08-01");
    httpRequest.setHeader("x-process-at", "ServiceBus");

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

    Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
    requestDoc.appendChild(entryElement);

    Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
    entryElement.appendChild(contentElement);

    Attr typeAttribute = requestDoc.createAttribute("type");
    typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8");
    contentElement.setAttributeNode(typeAttribute);

    Element topicDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "TopicDescription");
    contentElement.appendChild(topicDescriptionElement);

    if (topic.getDefaultMessageTimeToLive() != null) {
        Element defaultMessageTimeToLiveElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DefaultMessageTimeToLive");
        defaultMessageTimeToLiveElement
                .appendChild(requestDoc.createTextNode(topic.getDefaultMessageTimeToLive()));
        topicDescriptionElement.appendChild(defaultMessageTimeToLiveElement);
    }

    Element maxSizeInMegabytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes");
    maxSizeInMegabytesElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getMaxSizeInMegabytes())));
    topicDescriptionElement.appendChild(maxSizeInMegabytesElement);

    Element requiresDuplicateDetectionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "RequiresDuplicateDetection");
    requiresDuplicateDetectionElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isRequiresDuplicateDetection()).toLowerCase()));
    topicDescriptionElement.appendChild(requiresDuplicateDetectionElement);

    if (topic.getDuplicateDetectionHistoryTimeWindow() != null) {
        Element duplicateDetectionHistoryTimeWindowElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DuplicateDetectionHistoryTimeWindow");
        duplicateDetectionHistoryTimeWindowElement
                .appendChild(requestDoc.createTextNode(topic.getDuplicateDetectionHistoryTimeWindow()));
        topicDescriptionElement.appendChild(duplicateDetectionHistoryTimeWindowElement);
    }

    Element enableBatchedOperationsElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations");
    enableBatchedOperationsElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isEnableBatchedOperations()).toLowerCase()));
    topicDescriptionElement.appendChild(enableBatchedOperationsElement);

    Element sizeInBytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes");
    sizeInBytesElement.appendChild(requestDoc.createTextNode(Integer.toString(topic.getSizeInBytes())));
    topicDescriptionElement.appendChild(sizeInBytesElement);

    Element filteringMessagesBeforePublishingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "FilteringMessagesBeforePublishing");
    filteringMessagesBeforePublishingElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(topic.isFilteringMessagesBeforePublishing()).toLowerCase()));
    topicDescriptionElement.appendChild(filteringMessagesBeforePublishingElement);

    Element isAnonymousAccessibleElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible");
    isAnonymousAccessibleElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isAnonymousAccessible()).toLowerCase()));
    topicDescriptionElement.appendChild(isAnonymousAccessibleElement);

    if (topic.getAuthorizationRules() != null) {
        if (topic.getAuthorizationRules() instanceof LazyCollection == false
                || ((LazyCollection) topic.getAuthorizationRules()).isInitialized()) {
            Element authorizationRulesSequenceElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                    "AuthorizationRules");
            for (ServiceBusSharedAccessAuthorizationRule authorizationRulesItem : topic
                    .getAuthorizationRules()) {
                Element authorizationRuleElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                        "AuthorizationRule");
                authorizationRulesSequenceElement.appendChild(authorizationRuleElement);

                Attr typeAttribute2 = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                        "type");
                typeAttribute2.setValue("SharedAccessAuthorizationRule");
                authorizationRuleElement.setAttributeNode(typeAttribute2);

                if (authorizationRulesItem.getClaimType() != null) {
                    Element claimTypeElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType");
                    claimTypeElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimType()));
                    authorizationRuleElement.appendChild(claimTypeElement);
                }

                if (authorizationRulesItem.getClaimValue() != null) {
                    Element claimValueElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "ClaimValue");
                    claimValueElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimValue()));
                    authorizationRuleElement.appendChild(claimValueElement);
                }

                if (authorizationRulesItem.getRights() != null) {
                    if (authorizationRulesItem.getRights() instanceof LazyCollection == false
                            || ((LazyCollection) authorizationRulesItem.getRights()).isInitialized()) {
                        Element rightsSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        for (AccessRight rightsItem : authorizationRulesItem.getRights()) {
                            Element rightsItemElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                    "AccessRights");
                            rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                            rightsSequenceElement.appendChild(rightsItemElement);
                        }
                        authorizationRuleElement.appendChild(rightsSequenceElement);
                    }
                }

                Element createdTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                createdTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime())));
                authorizationRuleElement.appendChild(createdTimeElement);

                if (authorizationRulesItem.getKeyName() != null) {
                    Element keyNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName");
                    keyNameElement.appendChild(requestDoc.createTextNode(authorizationRulesItem.getKeyName()));
                    authorizationRuleElement.appendChild(keyNameElement);
                }

                Element modifiedTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
                modifiedTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime())));
                authorizationRuleElement.appendChild(modifiedTimeElement);

                if (authorizationRulesItem.getPrimaryKey() != null) {
                    Element primaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "PrimaryKey");
                    primaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getPrimaryKey()));
                    authorizationRuleElement.appendChild(primaryKeyElement);
                }

                if (authorizationRulesItem.getSecondaryKey() != null) {
                    Element secondaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SecondaryKey");
                    secondaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getSecondaryKey()));
                    authorizationRuleElement.appendChild(secondaryKeyElement);
                }
            }
            topicDescriptionElement.appendChild(authorizationRulesSequenceElement);
        }
    }

    if (topic.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status");
        statusElement.appendChild(requestDoc.createTextNode(topic.getStatus()));
        topicDescriptionElement.appendChild(statusElement);
    }

    Element createdAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedAt");
    SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat3.setTimeZone(TimeZone.getTimeZone("UTC"));
    createdAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat3.format(topic.getCreatedAt().getTime())));
    topicDescriptionElement.appendChild(createdAtElement);

    Element updatedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "UpdatedAt");
    SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat4.setTimeZone(TimeZone.getTimeZone("UTC"));
    updatedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat4.format(topic.getUpdatedAt().getTime())));
    topicDescriptionElement.appendChild(updatedAtElement);

    Element accessedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessedAt");
    SimpleDateFormat simpleDateFormat5 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat5.setTimeZone(TimeZone.getTimeZone("UTC"));
    accessedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat5.format(topic.getAccessedAt().getTime())));
    topicDescriptionElement.appendChild(accessedAtElement);

    Element supportOrderingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering");
    supportOrderingElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(topic.isSupportOrdering()).toLowerCase()));
    topicDescriptionElement.appendChild(supportOrderingElement);

    if (topic.getCountDetails() != null) {
        Element countDetailsElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails");
        topicDescriptionElement.appendChild(countDetailsElement);

        Element activeMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount");
        activeMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getActiveMessageCount())));
        countDetailsElement.appendChild(activeMessageCountElement);

        Element deadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount");
        deadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getDeadLetterMessageCount())));
        countDetailsElement.appendChild(deadLetterMessageCountElement);

        Element scheduledMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount");
        scheduledMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getScheduledMessageCount())));
        countDetailsElement.appendChild(scheduledMessageCountElement);

        Element transferDeadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                "TransferDeadLetterMessageCount");
        transferDeadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getTransferDeadLetterMessageCount())));
        countDetailsElement.appendChild(transferDeadLetterMessageCountElement);

        Element transferMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount");
        transferMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getTransferMessageCount())));
        countDetailsElement.appendChild(transferMessageCountElement);
    }

    Element subscriptionCountElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SubscriptionCount");
    subscriptionCountElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getSubscriptionCount())));
    topicDescriptionElement.appendChild(subscriptionCountElement);

    if (topic.getAutoDeleteOnIdle() != null) {
        Element autoDeleteOnIdleElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle");
        autoDeleteOnIdleElement.appendChild(requestDoc.createTextNode(topic.getAutoDeleteOnIdle()));
        topicDescriptionElement.appendChild(autoDeleteOnIdleElement);
    }

    if (topic.getEntityAvailabilityStatus() != null) {
        Element entityAvailabilityStatusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "EntityAvailabilityStatus");
        entityAvailabilityStatusElement
                .appendChild(requestDoc.createTextNode(topic.getEntityAvailabilityStatus()));
        topicDescriptionElement.appendChild(entityAvailabilityStatusElement);
    }

    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/atom+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
        ServiceBusTopicResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusTopicResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element titleElement = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "title");
                if (titleElement != null) {
                }

                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element topicDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "TopicDescription");
                    if (topicDescriptionElement2 != null) {
                        ServiceBusTopic topicDescriptionInstance = new ServiceBusTopic();
                        result.setTopic(topicDescriptionInstance);

                        Element defaultMessageTimeToLiveElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DefaultMessageTimeToLive");
                        if (defaultMessageTimeToLiveElement2 != null) {
                            String defaultMessageTimeToLiveInstance;
                            defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance);
                        }

                        Element maxSizeInMegabytesElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxSizeInMegabytes");
                        if (maxSizeInMegabytesElement2 != null) {
                            int maxSizeInMegabytesInstance;
                            maxSizeInMegabytesInstance = DatatypeConverter
                                    .parseInt(maxSizeInMegabytesElement2.getTextContent());
                            topicDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance);
                        }

                        Element requiresDuplicateDetectionElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresDuplicateDetection");
                        if (requiresDuplicateDetectionElement2 != null) {
                            boolean requiresDuplicateDetectionInstance;
                            requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean(
                                    requiresDuplicateDetectionElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance);
                        }

                        Element duplicateDetectionHistoryTimeWindowElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DuplicateDetectionHistoryTimeWindow");
                        if (duplicateDetectionHistoryTimeWindowElement2 != null) {
                            String duplicateDetectionHistoryTimeWindowInstance;
                            duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement2
                                    .getTextContent();
                            topicDescriptionInstance.setDuplicateDetectionHistoryTimeWindow(
                                    duplicateDetectionHistoryTimeWindowInstance);
                        }

                        Element enableBatchedOperationsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EnableBatchedOperations");
                        if (enableBatchedOperationsElement2 != null) {
                            boolean enableBatchedOperationsInstance;
                            enableBatchedOperationsInstance = DatatypeConverter.parseBoolean(
                                    enableBatchedOperationsElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setEnableBatchedOperations(enableBatchedOperationsInstance);
                        }

                        Element sizeInBytesElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SizeInBytes");
                        if (sizeInBytesElement2 != null) {
                            int sizeInBytesInstance;
                            sizeInBytesInstance = DatatypeConverter
                                    .parseInt(sizeInBytesElement2.getTextContent());
                            topicDescriptionInstance.setSizeInBytes(sizeInBytesInstance);
                        }

                        Element filteringMessagesBeforePublishingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "FilteringMessagesBeforePublishing");
                        if (filteringMessagesBeforePublishingElement2 != null) {
                            boolean filteringMessagesBeforePublishingInstance;
                            filteringMessagesBeforePublishingInstance = DatatypeConverter.parseBoolean(
                                    filteringMessagesBeforePublishingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setFilteringMessagesBeforePublishing(
                                    filteringMessagesBeforePublishingInstance);
                        }

                        Element isAnonymousAccessibleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "IsAnonymousAccessible");
                        if (isAnonymousAccessibleElement2 != null) {
                            boolean isAnonymousAccessibleInstance;
                            isAnonymousAccessibleInstance = DatatypeConverter
                                    .parseBoolean(isAnonymousAccessibleElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance);
                        }

                        Element authorizationRulesSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AuthorizationRules");
                        if (authorizationRulesSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AuthorizationRule")
                                    .size(); i1 = i1 + 1) {
                                org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                "AuthorizationRule")
                                        .get(i1));
                                ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                                topicDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance);

                                Element claimTypeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimType");
                                if (claimTypeElement2 != null) {
                                    String claimTypeInstance;
                                    claimTypeInstance = claimTypeElement2.getTextContent();
                                    authorizationRuleInstance.setClaimType(claimTypeInstance);
                                }

                                Element claimValueElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimValue");
                                if (claimValueElement2 != null) {
                                    String claimValueInstance;
                                    claimValueInstance = claimValueElement2.getTextContent();
                                    authorizationRuleInstance.setClaimValue(claimValueInstance);
                                }

                                Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "Rights");
                                if (rightsSequenceElement2 != null) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(rightsSequenceElement2,
                                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                    "AccessRights")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(rightsSequenceElement2,
                                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                        "AccessRights")
                                                .get(i2));
                                        authorizationRuleInstance.getRights()
                                                .add(AccessRight.valueOf(rightsElement.getTextContent()));
                                    }
                                }

                                Element createdTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "CreatedTime");
                                if (createdTimeElement2 != null) {
                                    Calendar createdTimeInstance;
                                    createdTimeInstance = DatatypeConverter
                                            .parseDateTime(createdTimeElement2.getTextContent());
                                    authorizationRuleInstance.setCreatedTime(createdTimeInstance);
                                }

                                Element keyNameElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "KeyName");
                                if (keyNameElement2 != null) {
                                    String keyNameInstance;
                                    keyNameInstance = keyNameElement2.getTextContent();
                                    authorizationRuleInstance.setKeyName(keyNameInstance);
                                }

                                Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ModifiedTime");
                                if (modifiedTimeElement2 != null) {
                                    Calendar modifiedTimeInstance;
                                    modifiedTimeInstance = DatatypeConverter
                                            .parseDateTime(modifiedTimeElement2.getTextContent());
                                    authorizationRuleInstance.setModifiedTime(modifiedTimeInstance);
                                }

                                Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "PrimaryKey");
                                if (primaryKeyElement2 != null) {
                                    String primaryKeyInstance;
                                    primaryKeyInstance = primaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setPrimaryKey(primaryKeyInstance);
                                }

                                Element secondaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "SecondaryKey");
                                if (secondaryKeyElement2 != null) {
                                    String secondaryKeyInstance;
                                    secondaryKeyInstance = secondaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance);
                                }
                            }
                        }

                        Element statusElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Status");
                        if (statusElement2 != null) {
                            String statusInstance;
                            statusInstance = statusElement2.getTextContent();
                            topicDescriptionInstance.setStatus(statusInstance);
                        }

                        Element createdAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedAt");
                        if (createdAtElement2 != null) {
                            Calendar createdAtInstance;
                            createdAtInstance = DatatypeConverter
                                    .parseDateTime(createdAtElement2.getTextContent());
                            topicDescriptionInstance.setCreatedAt(createdAtInstance);
                        }

                        Element updatedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "UpdatedAt");
                        if (updatedAtElement2 != null) {
                            Calendar updatedAtInstance;
                            updatedAtInstance = DatatypeConverter
                                    .parseDateTime(updatedAtElement2.getTextContent());
                            topicDescriptionInstance.setUpdatedAt(updatedAtInstance);
                        }

                        Element accessedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AccessedAt");
                        if (accessedAtElement2 != null) {
                            Calendar accessedAtInstance;
                            accessedAtInstance = DatatypeConverter
                                    .parseDateTime(accessedAtElement2.getTextContent());
                            topicDescriptionInstance.setAccessedAt(accessedAtInstance);
                        }

                        Element supportOrderingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SupportOrdering");
                        if (supportOrderingElement2 != null) {
                            boolean supportOrderingInstance;
                            supportOrderingInstance = DatatypeConverter
                                    .parseBoolean(supportOrderingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setSupportOrdering(supportOrderingInstance);
                        }

                        Element countDetailsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CountDetails");
                        if (countDetailsElement2 != null) {
                            CountDetails countDetailsInstance = new CountDetails();
                            topicDescriptionInstance.setCountDetails(countDetailsInstance);
                        }

                        Element subscriptionCountElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionCount");
                        if (subscriptionCountElement2 != null) {
                            int subscriptionCountInstance;
                            subscriptionCountInstance = DatatypeConverter
                                    .parseInt(subscriptionCountElement2.getTextContent());
                            topicDescriptionInstance.setSubscriptionCount(subscriptionCountInstance);
                        }

                        Element autoDeleteOnIdleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AutoDeleteOnIdle");
                        if (autoDeleteOnIdleElement2 != null) {
                            String autoDeleteOnIdleInstance;
                            autoDeleteOnIdleInstance = autoDeleteOnIdleElement2.getTextContent();
                            topicDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance);
                        }

                        Element entityAvailabilityStatusElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EntityAvailabilityStatus");
                        if (entityAvailabilityStatusElement2 != null) {
                            String entityAvailabilityStatusInstance;
                            entityAvailabilityStatusInstance = entityAvailabilityStatusElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setEntityAvailabilityStatus(entityAvailabilityStatusInstance);
                        }
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.compute.VirtualMachineExtensionOperationsImpl.java

/**
* The List Resource Extension Versions operation lists the versions of a
* resource extension that are available to add to a Virtual Machine. In
* Azure, a process can run as a resource extension of a Virtual Machine.
* For example, Remote Desktop Access or the Azure Diagnostics Agent can
* run as resource extensions to the Virtual Machine.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn495440.aspx for
* more information)//from   w  w w . j  a v a 2s  . com
*
* @param publisherName Required. The name of the publisher.
* @param extensionName Required. The name of the extension.
* @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.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The List Resource Extensions operation response.
*/
@Override
public VirtualMachineExtensionListResponse listVersions(String publisherName, String extensionName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (publisherName == null) {
        throw new NullPointerException("publisherName");
    }
    if (extensionName == null) {
        throw new NullPointerException("extensionName");
    }

    // 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("publisherName", publisherName);
        tracingParameters.put("extensionName", extensionName);
        CloudTracing.enter(invocationId, this, "listVersionsAsync", 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/resourceextensions/";
    url = url + URLEncoder.encode(publisherName, "UTF-8");
    url = url + "/";
    url = url + URLEncoder.encode(extensionName, "UTF-8");
    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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2015-04-01");

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element resourceExtensionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ResourceExtensions");
            if (resourceExtensionsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element resourceExtensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                            .get(i1));
                    VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension();
                    result.getResourceExtensions().add(resourceExtensionInstance);

                    Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Publisher");
                    if (publisherElement != null) {
                        String publisherInstance;
                        publisherInstance = publisherElement.getTextContent();
                        resourceExtensionInstance.setPublisher(publisherInstance);
                    }

                    Element nameElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        String nameInstance;
                        nameInstance = nameElement.getTextContent();
                        resourceExtensionInstance.setName(nameInstance);
                    }

                    Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Version");
                    if (versionElement != null) {
                        String versionInstance;
                        versionInstance = versionElement.getTextContent();
                        resourceExtensionInstance.setVersion(versionInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent();
                        resourceExtensionInstance.setLabel(labelInstance);
                    }

                    Element descriptionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Description");
                    if (descriptionElement != null) {
                        String descriptionInstance;
                        descriptionInstance = descriptionElement.getTextContent();
                        resourceExtensionInstance.setDescription(descriptionInstance);
                    }

                    Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PublicConfigurationSchema");
                    if (publicConfigurationSchemaElement != null) {
                        String publicConfigurationSchemaInstance;
                        publicConfigurationSchemaInstance = publicConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(publicConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPublicConfigurationSchema(publicConfigurationSchemaInstance);
                    }

                    Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PrivateConfigurationSchema");
                    if (privateConfigurationSchemaElement != null) {
                        String privateConfigurationSchemaInstance;
                        privateConfigurationSchemaInstance = privateConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(privateConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPrivateConfigurationSchema(privateConfigurationSchemaInstance);
                    }

                    Element sampleConfigElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SampleConfig");
                    if (sampleConfigElement != null) {
                        String sampleConfigInstance;
                        sampleConfigInstance = sampleConfigElement.getTextContent() != null
                                ? new String(Base64.decode(sampleConfigElement.getTextContent()))
                                : null;
                        resourceExtensionInstance.setSampleConfig(sampleConfigInstance);
                    }

                    Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "ReplicationCompleted");
                    if (replicationCompletedElement != null
                            && replicationCompletedElement.getTextContent() != null
                            && !replicationCompletedElement.getTextContent().isEmpty()) {
                        boolean replicationCompletedInstance;
                        replicationCompletedInstance = DatatypeConverter
                                .parseBoolean(replicationCompletedElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setReplicationCompleted(replicationCompletedInstance);
                    }

                    Element eulaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement != null) {
                        URI eulaInstance;
                        eulaInstance = new URI(eulaElement.getTextContent());
                        resourceExtensionInstance.setEula(eulaInstance);
                    }

                    Element privacyUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement.getTextContent());
                        resourceExtensionInstance.setPrivacyUri(privacyUriInstance);
                    }

                    Element homepageUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "HomepageUri");
                    if (homepageUriElement != null) {
                        URI homepageUriInstance;
                        homepageUriInstance = new URI(homepageUriElement.getTextContent());
                        resourceExtensionInstance.setHomepageUri(homepageUriInstance);
                    }

                    Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsJsonExtension");
                    if (isJsonExtensionElement != null && isJsonExtensionElement.getTextContent() != null
                            && !isJsonExtensionElement.getTextContent().isEmpty()) {
                        boolean isJsonExtensionInstance;
                        isJsonExtensionInstance = DatatypeConverter
                                .parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsJsonExtension(isJsonExtensionInstance);
                    }

                    Element isInternalExtensionElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "IsInternalExtension");
                    if (isInternalExtensionElement != null
                            && isInternalExtensionElement.getTextContent() != null
                            && !isInternalExtensionElement.getTextContent().isEmpty()) {
                        boolean isInternalExtensionInstance;
                        isInternalExtensionInstance = DatatypeConverter
                                .parseBoolean(isInternalExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsInternalExtension(isInternalExtensionInstance);
                    }

                    Element disallowMajorVersionUpgradeElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "DisallowMajorVersionUpgrade");
                    if (disallowMajorVersionUpgradeElement != null
                            && disallowMajorVersionUpgradeElement.getTextContent() != null
                            && !disallowMajorVersionUpgradeElement.getTextContent().isEmpty()) {
                        boolean disallowMajorVersionUpgradeInstance;
                        disallowMajorVersionUpgradeInstance = DatatypeConverter.parseBoolean(
                                disallowMajorVersionUpgradeElement.getTextContent().toLowerCase());
                        resourceExtensionInstance
                                .setDisallowMajorVersionUpgrade(disallowMajorVersionUpgradeInstance);
                    }

                    Element supportedOSElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SupportedOS");
                    if (supportedOSElement != null) {
                        String supportedOSInstance;
                        supportedOSInstance = supportedOSElement.getTextContent();
                        resourceExtensionInstance.setSupportedOS(supportedOSInstance);
                    }

                    Element companyNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "CompanyName");
                    if (companyNameElement != null) {
                        String companyNameInstance;
                        companyNameInstance = companyNameElement.getTextContent();
                        resourceExtensionInstance.setCompanyName(companyNameInstance);
                    }

                    Element publishedDateElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement != null && publishedDateElement.getTextContent() != null
                            && !publishedDateElement.getTextContent().isEmpty()) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement.getTextContent());
                        resourceExtensionInstance.setPublishedDate(publishedDateInstance);
                    }

                    Element regionsElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Regions");
                    if (regionsElement != null) {
                        String regionsInstance;
                        regionsInstance = regionsElement.getTextContent();
                        resourceExtensionInstance.setRegions(regionsInstance);
                    }
                }
            }

        }
        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:com.microsoft.windowsazure.management.compute.VirtualMachineOSImageOperationsImpl.java

/**
* The Create OS Image operation adds an operating system image that is
* stored in a storage account and is available from the image repository.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx
* for more information)//  w ww  .  jav a  2 s . c  om
*
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Image operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @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 ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Parameters returned from the Create Virtual Machine Image
* operation.
*/
@Override
public VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getMediaLinkUri() == null) {
        throw new NullPointerException("parameters.MediaLinkUri");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getOperatingSystemType() == null) {
        throw new NullPointerException("parameters.OperatingSystemType");
    }

    // 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/images";
    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", "2015-04-01");

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

    Element oSImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSImage");
    requestDoc.appendChild(oSImageElement);

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
    oSImageElement.appendChild(labelElement);

    Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "MediaLink");
    mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString()));
    oSImageElement.appendChild(mediaLinkElement);

    Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
    nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
    oSImageElement.appendChild(nameElement);

    Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS");
    osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType()));
    oSImageElement.appendChild(osElement);

    if (parameters.getEula() != null) {
        Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
        eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula()));
        oSImageElement.appendChild(eulaElement);
    }

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        oSImageElement.appendChild(descriptionElement);
    }

    if (parameters.getImageFamily() != null) {
        Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ImageFamily");
        imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily()));
        oSImageElement.appendChild(imageFamilyElement);
    }

    if (parameters.getPublishedDate() != null) {
        Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublishedDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        publishedDateElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
        oSImageElement.appendChild(publishedDateElement);
    }

    Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsPremium");
    isPremiumElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase()));
    oSImageElement.appendChild(isPremiumElement);

    Element showInGuiElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ShowInGui");
    showInGuiElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isShowInGui()).toLowerCase()));
    oSImageElement.appendChild(showInGuiElement);

    if (parameters.getPrivacyUri() != null) {
        Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PrivacyUri");
        privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
        oSImageElement.appendChild(privacyUriElement);
    }

    if (parameters.getIconUri() != null) {
        Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IconUri");
        iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri()));
        oSImageElement.appendChild(iconUriElement);
    }

    if (parameters.getRecommendedVMSize() != null) {
        Element recommendedVMSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
        recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize()));
        oSImageElement.appendChild(recommendedVMSizeElement);
    }

    if (parameters.getSmallIconUri() != null) {
        Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SmallIconUri");
        smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri()));
        oSImageElement.appendChild(smallIconUriElement);
    }

    if (parameters.getLanguage() != null) {
        Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Language");
        languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage()));
        oSImageElement.appendChild(languageElement);
    }

    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
        VirtualMachineOSImageCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualMachineOSImageCreateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element oSImageElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OSImage");
            if (oSImageElement2 != null) {
                Element locationElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Location");
                if (locationElement != null) {
                    String locationInstance;
                    locationInstance = locationElement.getTextContent();
                    result.setLocation(locationInstance);
                }

                Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Category");
                if (categoryElement != null) {
                    String categoryInstance;
                    categoryInstance = categoryElement.getTextContent();
                    result.setCategory(categoryInstance);
                }

                Element labelElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Label");
                if (labelElement2 != null) {
                    String labelInstance;
                    labelInstance = labelElement2.getTextContent();
                    result.setLabel(labelInstance);
                }

                Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                if (logicalSizeInGBElement != null) {
                    double logicalSizeInGBInstance;
                    logicalSizeInGBInstance = DatatypeConverter
                            .parseDouble(logicalSizeInGBElement.getTextContent());
                    result.setLogicalSizeInGB(logicalSizeInGBInstance);
                }

                Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "MediaLink");
                if (mediaLinkElement2 != null) {
                    URI mediaLinkInstance;
                    mediaLinkInstance = new URI(mediaLinkElement2.getTextContent());
                    result.setMediaLinkUri(mediaLinkInstance);
                }

                Element nameElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement2 != null) {
                    String nameInstance;
                    nameInstance = nameElement2.getTextContent();
                    result.setName(nameInstance);
                }

                Element osElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "OS");
                if (osElement2 != null) {
                    String osInstance;
                    osInstance = osElement2.getTextContent();
                    result.setOperatingSystemType(osInstance);
                }

                Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Eula");
                if (eulaElement2 != null) {
                    String eulaInstance;
                    eulaInstance = eulaElement2.getTextContent();
                    result.setEula(eulaInstance);
                }

                Element descriptionElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Description");
                if (descriptionElement2 != null) {
                    String descriptionInstance;
                    descriptionInstance = descriptionElement2.getTextContent();
                    result.setDescription(descriptionInstance);
                }

                Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                if (imageFamilyElement2 != null) {
                    String imageFamilyInstance;
                    imageFamilyInstance = imageFamilyElement2.getTextContent();
                    result.setImageFamily(imageFamilyInstance);
                }

                Element publishedDateElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                if (publishedDateElement2 != null && publishedDateElement2.getTextContent() != null
                        && !publishedDateElement2.getTextContent().isEmpty()) {
                    Calendar publishedDateInstance;
                    publishedDateInstance = DatatypeConverter
                            .parseDateTime(publishedDateElement2.getTextContent());
                    result.setPublishedDate(publishedDateInstance);
                }

                Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublisherName");
                if (publisherNameElement != null) {
                    String publisherNameInstance;
                    publisherNameInstance = publisherNameElement.getTextContent();
                    result.setPublisherName(publisherNameInstance);
                }

                Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsPremium");
                if (isPremiumElement2 != null && isPremiumElement2.getTextContent() != null
                        && !isPremiumElement2.getTextContent().isEmpty()) {
                    boolean isPremiumInstance;
                    isPremiumInstance = DatatypeConverter
                            .parseBoolean(isPremiumElement2.getTextContent().toLowerCase());
                    result.setIsPremium(isPremiumInstance);
                }

                Element showInGuiElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                if (showInGuiElement2 != null && showInGuiElement2.getTextContent() != null
                        && !showInGuiElement2.getTextContent().isEmpty()) {
                    boolean showInGuiInstance;
                    showInGuiInstance = DatatypeConverter
                            .parseBoolean(showInGuiElement2.getTextContent().toLowerCase());
                    result.setShowInGui(showInGuiInstance);
                }

                Element privacyUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                if (privacyUriElement2 != null) {
                    URI privacyUriInstance;
                    privacyUriInstance = new URI(privacyUriElement2.getTextContent());
                    result.setPrivacyUri(privacyUriInstance);
                }

                Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IconUri");
                if (iconUriElement2 != null) {
                    String iconUriInstance;
                    iconUriInstance = iconUriElement2.getTextContent();
                    result.setIconUri(iconUriInstance);
                }

                Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                if (recommendedVMSizeElement2 != null) {
                    String recommendedVMSizeInstance;
                    recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent();
                    result.setRecommendedVMSize(recommendedVMSizeInstance);
                }

                Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                if (smallIconUriElement2 != null) {
                    String smallIconUriInstance;
                    smallIconUriInstance = smallIconUriElement2.getTextContent();
                    result.setSmallIconUri(smallIconUriInstance);
                }

                Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Language");
                if (languageElement2 != null) {
                    String languageInstance;
                    languageInstance = languageElement2.getTextContent();
                    result.setLanguage(languageInstance);
                }

                Element iOTypeElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IOType");
                if (iOTypeElement != null) {
                    String iOTypeInstance;
                    iOTypeInstance = iOTypeElement.getTextContent();
                    result.setIOType(iOTypeInstance);
                }
            }

        }
        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();
        }
    }
}