Example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode

List of usage examples for com.fasterxml.jackson.databind ObjectMapper createObjectNode

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode.

Prototype

@Override
public ObjectNode createObjectNode() 

Source Link

Document

Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

Usage

From source file:com.hrm.controller.RegisterController.java

@RequestMapping("stuRegister")
@ResponseBody/* w w  w  .  j  av  a 2s .  co  m*/
public void StuRegister(@ModelAttribute StuModel stuRegisterModel, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    /*???*/
    response.setContentType("application/json");
    int checkAmount = 0;
    PrintWriter out = response.getWriter();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode register = mapper.createObjectNode();
    String StuAccount = request.getParameter("username");
    String agentId = request.getParameter("agentId");
    String StuPassword = string2MD5(request.getParameter("password"));
    String username = VerifyCodeUtil.getRandomString(16);
    String method = request.getParameter("method");
    String stuMsg = request.getParameter("stuMsg");
    if (agentId == null || agentId.equals("")) {
        agentId = "0";
    }
    if (method != null) {
        if (stuMsg != null) {
            if (session.getAttribute("telephoneCodeSession") != null
                    && session.getAttribute("telephoneSession") != null) {
                System.out.println(session.getAttribute("telephoneCodeSession"));
                System.out.println(session.getAttribute("telephoneSession"));
                if (session.getAttribute("telephoneCodeSession").equals(stuMsg)
                        && session.getAttribute("telephoneSession").equals(StuAccount)) {
                    checkAmount = IComServiceImplRegister.accountCheckService(
                            StuAccount);/*??checkAmount1??*/
                    if (checkAmount == 0) {
                        System.out.print("agentId:" + agentId);
                        stuRegisterModel = StuService.saveStuInfo(StuAccount, StuPassword, username, agentId);
                        if (stuRegisterModel != null) {
                            stuRegisterModel.setPassword(null);
                            session.setAttribute("loginInfoSession", stuRegisterModel);
                            register.put("status", "??");
                            /*out.write(mapper.writeValueAsString(stuRegisterModel));*//*?*/
                            out.write(register.toString());
                        } else {
                            register.put("status", "??");
                            out.write(register.toString());
                        }
                    } else {
                        register.put("status", "?");
                        out.write(register.toString());/*?*/
                    }
                } else {
                    register.put("status", "???");
                    out.write(register.toString());
                }
            } else {
                register.put("status", "??????");
                out.write(register.toString());
            }
        } else {
            register.put("status", "???");
            out.write(register.toString());
        }
    } else {/*PC*/
        checkAmount = IComServiceImplRegister.accountCheckService(
                StuAccount);/*??checkAmount1??*/
        if (checkAmount == 0) {
            System.out.print("agentId:" + agentId);
            if (session.getAttribute("telephoneCodeSession").equals(stuMsg)
                    && session.getAttribute("telephoneSession").equals(StuAccount)) {
                stuRegisterModel = StuService.saveStuInfo(StuAccount, StuPassword, username, agentId);//
                if (stuRegisterModel != null) {
                    stuRegisterModel.setPassword(null);
                    session.setAttribute("loginInfoSession", stuRegisterModel);
                    session.setAttribute("accountLableInfoSession", "stu");
                    System.out.println(JSONObject.fromObject(stuRegisterModel));
                    register.put("registerStatus", "1");
                    register.put("accountClass", "stu");
                    out.write(register.toString());/*?*/
                } else {
                    System.out.print("??");
                    register.put("registerStatus", "0");
                    out.write(register.toString());/*?*/
                }
            } else {
                System.out.print("?????");
                register.put("registerStatus", "2");
                out.write(register.toString());/*?*/
            }
        } else {
            System.out.print("?");
            register.put("registerStatus", "-1");
            out.write(register.toString());/*?*/
        }
    }
}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

private ObjectNode buildLinkRelationNode(final ObjectMapper objectMapper, final LinkRelation linkRelation) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final ObjectNode linkRelationNode = objectMapper.createObjectNode();

    linkRelationNode.put(PropertyName.uri.name(), syntaxLoader.formatSyntaxValue(linkRelation.getUri()));

    final UniqueName linkRelationUniqueName = linkRelation.getUniqueName();
    linkRelationNode.put(PropertyName.uniqueName.name(),
            syntaxLoader.formatSyntaxValue(linkRelationUniqueName));
    linkRelationNode.put(PropertyName.title.name(), linkRelation.getTitle());

    final String description = linkRelation.getDescription();
    if (StringUtils.isNotBlank(description)) {
        linkRelationNode.put(PropertyName.description.name(), description);
    }// w  ww .java2  s . c  o m

    linkRelationNode.put(PropertyName.version.name(), linkRelation.getVersion());
    linkRelationNode.put(PropertyName.method.name(), linkRelation.getMethod().getProtocolGivenName());

    final URI responseSchemaUri = linkRelation.getResponseSchemaUri();
    if (responseSchemaUri != null) {
        final ObjectNode responseSchemaNode = SchemaDesignFormatter.buildSchemaNode(objectMapper,
                responseSchemaUri, schemaLoader, null);
        linkRelationNode.put(PropertyName.responseSchema.name(), responseSchemaNode);
    }

    final URI requestSchemaUri = linkRelation.getRequestSchemaUri();
    if (requestSchemaUri != null) {
        final ObjectNode requestSchemaNode = SchemaDesignFormatter.buildSchemaNode(objectMapper,
                requestSchemaUri, schemaLoader, null);
        linkRelationNode.put(PropertyName.requestSchema.name(), requestSchemaNode);
    }

    final String linkRelationName = linkRelationUniqueName.getLocalName();
    final String signature = buildLinkSignature(linkRelationName, responseSchemaUri, requestSchemaUri, null);
    linkRelationNode.put(PropertyName.signature.name(), signature);

    return linkRelationNode;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Returns a JsonNode with the field's mapping
 * @param tokenize_dual// www  .j av  a  2 s .c om
 * @param defaults
 * @return
 */
protected static JsonNode getMapping(final Tuple2<Boolean, Boolean> tokenize_dual,
        final SearchIndexSchemaDefaultBean defaults, final ObjectMapper mapper, boolean is_dynamic_template) {
    return Optional
            .of(Patterns.match(tokenize_dual).<JsonNode>andReturn()
                    .when(td -> td.equals(Tuples._2T(true, true)),
                            __ -> mapper.convertValue(defaults.dual_tokenized_string_field(), JsonNode.class))
                    .when(td -> td.equals(Tuples._2T(true, false)),
                            __ -> mapper.convertValue(defaults.tokenized_string_field(), JsonNode.class))
                    .when(td -> td.equals(Tuples._2T(false, true)),
                            __ -> mapper.convertValue(defaults.dual_untokenized_string_field(), JsonNode.class))
                    .when(td -> td.equals(Tuples._2T(false, false)),
                            __ -> mapper.convertValue(defaults.untokenized_string_field(), JsonNode.class))
                    .otherwiseAssert())
            .map(j -> is_dynamic_template ? mapper.createObjectNode().set("mapping", j) : j).get();

}

From source file:com.hrm.controller.RegisterController.java

@RequestMapping("comSupplement")
public void ComInfoSupplement(HttpSession session, HttpServletResponse response,
        MultipartHttpServletRequest Mrequest, HttpServletRequest request) throws IOException {
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) Mrequest;
    ComModel comSupplementModel = new ComModel();
    PrintWriter out = response.getWriter();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode supplement = mapper.createObjectNode();
    Map<String, Object> dataMap = new HashMap<String, Object>();
    String iconImgUrl = null;//  w w  w . j av  a 2  s  .  c  om
    String licenseImgUrl = null;/*??*/
    String taxImgUrl = null;
    int checked = 1;
    String method = multipartHttpServletRequest.getParameter("method");
    String companyId = multipartHttpServletRequest.getParameter("companyId");
    String telephone = multipartHttpServletRequest.getParameter("telephone");/*?*/
    String name = multipartHttpServletRequest.getParameter("name");
    String label = multipartHttpServletRequest.getParameter("label");
    String describes = multipartHttpServletRequest.getParameter("describes");
    String province = multipartHttpServletRequest.getParameter("province");
    String city = multipartHttpServletRequest.getParameter("city");
    String region = multipartHttpServletRequest.getParameter("region");
    String details = multipartHttpServletRequest.getParameter("details");
    String linkMan = multipartHttpServletRequest.getParameter("linkMan");
    String linkPhone = multipartHttpServletRequest.getParameter("linkPhone");
    String email = multipartHttpServletRequest.getParameter("email");
    String role = multipartHttpServletRequest.getParameter("role");
    if (role != null) {
        comSupplementModel.setRole(Integer.parseInt(role));
    }
    MultipartFile iconfile = multipartHttpServletRequest.getFile("icon");
    MultipartFile licenseImgfile = multipartHttpServletRequest.getFile("license");
    MultipartFile taxImgfile = multipartHttpServletRequest.getFile("tax");
    System.out.println("iconfile:" + iconfile);
    if (iconfile != null) {
        if (!((MultipartFile) iconfile).isEmpty()) {
            String imgIconUrl;
            boolean deleteIcon;
            comSupplementModel = loginDao.selectByCompanyId(Integer.parseInt(companyId));
            /*             if(comSupplementModel.getIsCheck()==0){
                            System.out.println(""+comSupplementModel.getIsCheck());
                            checked=1;
                         }*/
            imgIconUrl = comSupplementModel.getIcno();
            if (imgIconUrl != null) {
                System.out.println();
                imgIconUrl = imgIconUrl.substring(5);
                deleteIcon = deleteFile(request, imgIconUrl);//
                if (deleteIcon) {
                    System.out.println("??");
                } else {
                    System.out.println("?");
                }
            }
            iconImgUrl = SaveImg(request, iconfile, iconImgUrl, 1, "1", "companyinfo");
        }
    }
    if (licenseImgfile != null) {
        if (!((MultipartFile) licenseImgfile).isEmpty()) {
            String imgLicenseUrl;
            boolean deleteIcon;
            comSupplementModel = loginDao.selectByCompanyId(Integer.parseInt(companyId));
            imgLicenseUrl = comSupplementModel.getLicense();
            if (imgLicenseUrl != null) {
                System.out.println();
                imgLicenseUrl = imgLicenseUrl.substring(5);
                deleteIcon = deleteFile(request, imgLicenseUrl);//
                if (deleteIcon) {
                    System.out.println("??");
                } else {
                    System.out.println("?");
                }
            }
            licenseImgUrl = SaveImg(request, licenseImgfile, licenseImgUrl, 2, "1", "companyinfo");
        }
    }
    if (taxImgfile != null) {
        if (!((MultipartFile) taxImgfile).isEmpty()) {
            String imgTaxUrl;
            boolean deleteIcon;
            comSupplementModel = loginDao.selectByCompanyId(Integer.parseInt(companyId));
            /*             if(comSupplementModel.getIsCheck()==0){
                            System.out.println(""+comSupplementModel.getIsCheck());
                            checked=1;
                         }*/
            imgTaxUrl = comSupplementModel.getTax();
            if (imgTaxUrl != null) {
                System.out.println();
                imgTaxUrl = imgTaxUrl.substring(5);
                deleteIcon = deleteFile(request, imgTaxUrl);//
                if (deleteIcon) {
                    System.out.println("??");
                } else {
                    System.out.println("?");
                }
            }
            taxImgUrl = SaveImg(request, taxImgfile, taxImgUrl, 3, "1", "companyinfo");
        }
    }
    if (iconImgUrl != null) {
        comSupplementModel.setIcno(iconImgUrl);
    }
    if (licenseImgUrl != null) {
        comSupplementModel.setIcno(licenseImgUrl);
    }
    if (taxImgUrl != null) {
        comSupplementModel.setIcno(taxImgUrl);
    }
    System.out.println(telephone);
    comSupplementModel.setCom(telephone, name, iconImgUrl, label, describes, province, city, region, details,
            licenseImgUrl, taxImgUrl, linkMan, linkPhone, email);
    if (checked == 1) {
        System.out.println("" + comSupplementModel.getId());
        comSupplementModel.setIsCheck(1);
    }
    int amount = comSupplementService.comInfoSupplementService(comSupplementModel);
    if (amount > 0) {
        comSupplementModel = loginDao.selectByCompanyId(Integer.parseInt(companyId));
        System.out.println(comSupplementModel.getDescribes());
        if (method != null) {
            session.setAttribute("loginInfoSession", comSupplementModel);
            out.write("1");
            dataMap.put("status", 1);
            dataMap.put("tax", comSupplementModel.getTax());
            dataMap.put("license", comSupplementModel.getLicense());
            dataMap.put("icon", comSupplementModel.getIcno());
            JSONObject json = JSONObject.fromObject(dataMap);
            System.out.println(json.toString());
        } else {
            dataMap.put("status", 1);
            dataMap.put("tax", comSupplementModel.getTax());
            dataMap.put("license", comSupplementModel.getLicense());
            dataMap.put("icon", comSupplementModel.getIcno());
            JSONObject json = JSONObject.fromObject(dataMap);
            out.write(json.toString());
        }
        System.out.println("???");
    } else {
        if (method != null) {//PC
            out.write("0");
        } else {
            dataMap.put("status", 0);
            JSONObject json = JSONObject.fromObject(dataMap);
            out.write(json.toString());
        }
    }
}

From source file:org.onosproject.sse.SseTopologyViewMessages.java

private ObjectNode hostConnect(ObjectMapper mapper, HostLocation location) {
    return mapper.createObjectNode().put("device", location.deviceId().toString()).put("port",
            location.port().toLong());//from  www . j av a2  s .  co m
}

From source file:org.onosproject.sse.SseTopologyViewMessages.java

private ObjectNode json(String id, String type, Prop... props) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode result = mapper.createObjectNode().put("id", id).put("type", type);
    ObjectNode pnode = mapper.createObjectNode();
    ArrayNode porder = mapper.createArrayNode();
    for (Prop p : props) {
        porder.add(p.key);/* w w  w . j a  v a2s  .  c om*/
        pnode.put(p.key, p.value);
    }
    result.set("propOrder", porder);
    result.set("props", pnode);
    return result;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Utility function to create a mapping out of all the different system components (see also ElasticsearchUtils)
 * @param bucket//from   ww w  . j a  va  2  s  . co  m
 * @param config
 * @return
 */
public static XContentBuilder createIndexMapping(final DataBucketBean bucket,
        final Optional<String> secondary_buffer, final boolean is_primary,
        final ElasticsearchIndexServiceConfigBean schema_config, final ObjectMapper mapper,
        final String index_type) {
    final JsonNode default_mapping = mapper.convertValue(schema_config.search_technology_override(),
            JsonNode.class);

    // Also get JsonNodes for the default field config bit

    final boolean columnar_enabled = Optional.ofNullable(bucket.data_schema())
            .map(DataSchemaBean::columnar_schema).filter(s -> Optional.ofNullable(s.enabled()).orElse(true))
            .isPresent();

    final boolean doc_enabled = Optional.ofNullable(bucket.data_schema()).map(DataSchemaBean::document_schema)
            .filter(s -> Optional.ofNullable(s.enabled()).orElse(true)).isPresent();

    // (these can't be null by construction)
    final JsonNode enabled_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().enabled_field_data_analyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode enabled_not_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().enabled_field_data_notanalyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode default_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().default_field_data_analyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode default_not_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().default_field_data_notanalyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final Optional<JsonNode> doc_schema = doc_enabled
            ? Optional.ofNullable(mapper.convertValue(schema_config.document_schema_override(), JsonNode.class))
            : Optional.empty();

    // Get a list of field overrides Either<String,Tuple2<String,String>> for dynamic/real fields

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups = ElasticsearchIndexUtils
            .parseDefaultMapping(default_mapping,
                    (CollidePolicy.new_type == Optional
                            .ofNullable(schema_config.search_technology_override().collide_policy())
                            .orElse(CollidePolicy.new_type))
                                    ? Optional.empty()
                                    : Optional.ofNullable(
                                            schema_config.search_technology_override().type_name_or_prefix()),
                    Optionals.of(() -> bucket.data_schema().search_index_schema()),
                    Optionals.of(() -> bucket.data_schema().document_schema()),
                    schema_config.search_technology_override(), mapper);

    // If a time field is present then adding the default mapping for it (overwrite @timestamp if that's the specified field):

    final Optional<JsonNode> time_mapping = Optional.ofNullable(schema_config.temporal_technology_override())
            .map(DataSchemaBean.TemporalSchemaBean::technology_override_schema)
            .map(t -> (Object) t.get("default_timefield_mapping"))
            .map(js -> mapper.convertValue(js, JsonNode.class));
    time_mapping.ifPresent(json -> {
        Optional.ofNullable(bucket.data_schema()).map(DataSchemaBean::temporal_schema)
                .filter(s -> Optional.ofNullable(s.enabled()).orElse(true)).map(t -> t.time_field())
                .ifPresent(time_field -> {
                    field_lookups.put(Either.left(time_field), json); //(MUTABLE CODE WARNING)
                });
    });

    final XContentBuilder test_result = getFullMapping(bucket, secondary_buffer, is_primary, schema_config,
            field_lookups, enabled_not_analyzed_field, enabled_analyzed_field, default_not_analyzed_field,
            default_analyzed_field, doc_schema, schema_config.search_technology_override(), mapper, index_type);

    return test_result;
}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

protected ObjectNode buildResourceNode(final ObjectMapper objectMapper, final Map<URI, ObjectNode> schemaNodes,
        final Map<URI, LinkRelation> linkRelationCache, final ApiNavigator apiNavigator,
        final Resource resource) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final ObjectNode resourceNode = objectMapper.createObjectNode();

    resourceNode.put(PropertyName.id.name(), syntaxLoader.formatSyntaxValue(resource.getResourceTemplateId()));
    resourceNode.put(PropertyName.pathSegment.name(), resource.getPathSegment());
    resourceNode.put(PropertyName.fullPath.name(), resource.getPathText());

    final String parentPathText = resource.getParentPathText();
    if (parentPathText != null) {
        resourceNode.put(PropertyName.parentPath.name(), parentPathText);
    }/*w ww  .j a v a2 s .com*/

    resourceNode.put(PropertyName.uriTemplate.name(), resource.getUriTemplate().getUriTemplateString());

    final URI defaultSchemaUri = resource.getDefaultSchemaUri();
    Prototype defaultPrototype = null;
    if (defaultSchemaUri != null) {
        final ObjectNode defaultSchemaNode = getSchemaNode(objectMapper, schemaNodes, defaultSchemaUri,
                schemaLoader);
        resourceNode.put(PropertyName.defaultSchema.name(), defaultSchemaNode);
        defaultPrototype = schemaLoader.getPrototype(defaultSchemaUri);
    }

    final ArrayNode referencesNode = buildReferencesArrayNode(objectMapper, schemaNodes, linkRelationCache,
            resource, defaultPrototype);
    if (referencesNode.size() > 0) {
        resourceNode.put(PropertyName.references.name(), referencesNode);
    }

    final ObjectNode linksNode = buildLinksNode(objectMapper, schemaNodes, linkRelationCache, apiNavigator,
            resource, defaultPrototype);
    if (linksNode.size() > 0) {
        resourceNode.put(PropertyName.links.name(), linksNode);
    }

    return resourceNode;
}

From source file:com.ikanow.aleph2.data_model.utils.TestJsonUtils.java

@Test
public void test_foldTuple() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    LinkedHashMap<String, Object> test1 = new LinkedHashMap<String, Object>();
    test1.put("long", 10L);
    test1.put("double", 1.1);
    test1.put("string", "val");
    test1.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");

    final JsonNode j1 = JsonUtils.foldTuple(test1, mapper, Optional.empty());
    assertEquals("{\"misc\":true,\"long\":10,\"string\":\"val\",\"double\":1.1}", j1.toString());

    LinkedHashMap<String, Object> test2 = new LinkedHashMap<String, Object>();
    test2.put("misc", false);
    test2.put("long", 10L);
    test2.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");
    test2.put("double", 1.1);
    test2.put("string", "val");

    final JsonNode j2 = JsonUtils.foldTuple(test2, mapper, Optional.of("json"));
    assertEquals("{\"misc\":false,\"long\":10,\"string\":\"val\",\"double\":1.1}", j2.toString());

    LinkedHashMap<String, Object> test3 = new LinkedHashMap<String, Object>();
    test3.put("long", mapper.createObjectNode());
    test3.put("double", mapper.createArrayNode());
    test3.put("string", BeanTemplateUtils.build(TestBean.class).with("test1", 4).done().get());
    test3.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");

    final JsonNode j3 = JsonUtils.foldTuple(test3, mapper, Optional.of("json"));
    assertEquals("{\"misc\":true,\"long\":{},\"string\":{\"test1\":4},\"double\":[]}", j3.toString());

    LinkedHashMap<String, Object> test4 = new LinkedHashMap<String, Object>();
    test4.put("misc", BigDecimal.ONE);
    test4.put("long", (int) 10);
    test4.put("double", (float) 1.1);
    test4.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");
    test4.put("string", "val");

    final JsonNode j4 = JsonUtils.foldTuple(test4, mapper, Optional.of("json"));
    assertEquals("{\"misc\":1,\"long\":10,\"string\":\"val\",\"double\":1.1}",
            j4.toString().replaceFirst("1[.]1[0]{6,}[0-9]+", "1.1"));

    try {//w w w  .  j a v a2  s.c  om
        test4.put("json", "{\"misc\":true,\"long\":1, string\":\"\"}"); // (Added json error)
        JsonUtils.foldTuple(test4, mapper, Optional.of("json"));
        fail("Should have thrown JSON exception");
    } catch (Exception e) {
    } // json error, check

    new JsonUtils(); // (just for coverage)      
}

From source file:com.microsoft.azure.vmagent.AzureVMManagementServiceDelegate.java

public static AzureVMDeploymentInfo createDeployment(final AzureVMAgentTemplate template,
        final int numberOfAgents, TokenCache tokenCache,
        AzureVMAgentCleanUpTask.DeploymentRegistrar deploymentRegistrar)
        throws AzureCloudException, IOException {

    InputStream embeddedTemplate = null;
    try {/*ww  w  .j  a  va  2 s  .c  om*/
        LOGGER.log(Level.INFO,
                "AzureVMManagementServiceDelegate: createDeployment: Initializing deployment for agentTemplate {0}",
                template.getTemplateName());

        final Azure azureClient = tokenCache.getAzureClient();

        final Date timestamp = new Date(System.currentTimeMillis());
        final String deploymentName = AzureUtil.getDeploymentName(template.getTemplateName(), timestamp);
        final String vmBaseName = AzureUtil.getVMBaseName(template.getTemplateName(), deploymentName,
                template.getOsType(), numberOfAgents);
        final String locationName = getLocationName(template.getLocation());
        final String storageAccountName = template.getStorageAccountName();
        if (!template.getResourceGroupName().matches(Constants.DEFAULT_RESOURCE_GROUP_PATTERN)) {
            LOGGER.log(Level.SEVERE,
                    "AzureVMManagementServiceDelegate: createDeployment: ResourceGroup Name {0} is invalid. It should be 1-64 alphanumeric characters",
                    new Object[] { template.getResourceGroupName() });
            throw new Exception("ResourceGroup Name is invalid");
        }
        final String resourceGroupName = template.getResourceGroupName();
        LOGGER.log(Level.INFO,
                "AzureVMManagementServiceDelegate: createDeployment: Creating a new deployment {0} with VM base name {1}",
                new Object[] { deploymentName, vmBaseName });

        createAzureResourceGroup(azureClient, locationName, resourceGroupName);
        //For blob endpoint url in arm template, it's different based on different environments
        //So create StorageAccount and get suffix 
        createStorageAccount(azureClient, storageAccountName, locationName, resourceGroupName);
        StorageAccount storageAccount = getStorageAccount(azureClient, storageAccountName, resourceGroupName);
        String blobEndpointSuffix = getBlobEndpointSuffixForTemplate(storageAccount);
        final boolean useCustomScriptExtension = template.getOsType().equals(Constants.OS_TYPE_WINDOWS)
                && !StringUtils.isBlank(template.getInitScript())
                && template.getAgentLaunchMethod().equals(Constants.LAUNCH_METHOD_JNLP);

        // check if a custom image id has been provided otherwise work with publisher and offer
        if (template.getImageReferenceType().equals(IMAGE_CUSTOM_REFERENCE)) {
            if (useCustomScriptExtension) {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template {0}",
                        EMBEDDED_TEMPLATE_IMAGE_WITH_SCRIPT_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_IMAGE_WITH_SCRIPT_FILENAME);
            } else {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template (with script) {0}",
                        EMBEDDED_TEMPLATE_IMAGE_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_IMAGE_FILENAME);
            }
        } else {
            if (useCustomScriptExtension) {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template (with script) {0}",
                        EMBEDDED_TEMPLATE_WITH_SCRIPT_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_WITH_SCRIPT_FILENAME);
            } else {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template {0}",
                        EMBEDDED_TEMPLATE_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_FILENAME);
            }
        }

        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode tmp = mapper.readTree(embeddedTemplate);

        // Add count variable for loop....
        final ObjectNode count = mapper.createObjectNode();
        count.put("type", "int");
        count.put("defaultValue", numberOfAgents);
        ObjectNode.class.cast(tmp.get("parameters")).replace("count", count);

        ObjectNode.class.cast(tmp.get("variables")).put("vmName", vmBaseName);
        ObjectNode.class.cast(tmp.get("variables")).put("location", locationName);
        ObjectNode.class.cast(tmp.get("variables")).put("jenkinsTag", Constants.AZURE_JENKINS_TAG_VALUE);
        ObjectNode.class.cast(tmp.get("variables")).put("resourceTag",
                deploymentRegistrar.getDeploymentTag().get());

        if (StringUtils.isNotBlank(template.getImagePublisher())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imagePublisher", template.getImagePublisher());
        }

        if (StringUtils.isNotBlank(template.getImageOffer())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imageOffer", template.getImageOffer());
        }

        if (StringUtils.isNotBlank(template.getImageSku())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imageSku", template.getImageSku());
        }

        if (StringUtils.isNotBlank(template.getOsType())) {
            ObjectNode.class.cast(tmp.get("variables")).put("osType", template.getOsType());
        }

        if (StringUtils.isNotBlank(template.getImage())) {
            ObjectNode.class.cast(tmp.get("variables")).put("image", template.getImage());
        }

        // If using the custom script extension (vs. SSH) to startup the powershell scripts,
        // add variables for that and upload the init script to the storage account
        if (useCustomScriptExtension) {
            ObjectNode.class.cast(tmp.get("variables")).put("jenkinsServerURL",
                    Jenkins.getInstance().getRootUrl());
            // Calculate the client secrets.  The secrets are based off the machine name,
            ArrayNode clientSecretsNode = ObjectNode.class.cast(tmp.get("variables")).putArray("clientSecrets");
            for (int i = 0; i < numberOfAgents; i++) {
                clientSecretsNode
                        .add(JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(String.format("%s%d", vmBaseName, i)));
            }
            // Upload the startup script to blob storage
            String scriptName = String.format("%s%s", deploymentName, "init.ps1");
            String scriptUri = uploadCustomScript(template, scriptName, tokenCache);
            ObjectNode.class.cast(tmp.get("variables")).put("startupScriptURI", scriptUri);
            ObjectNode.class.cast(tmp.get("variables")).put("startupScriptName", scriptName);

            List<StorageAccountKey> storageKeys = azureClient.storageAccounts()
                    .getByGroup(template.getResourceGroupName(), storageAccountName).getKeys();
            if (storageKeys.isEmpty()) {
                throw new AzureCloudException("AzureVMManagementServiceDelegate: createDeployment: "
                        + "Exception occured while fetching the storage account key");
            }
            String storageAccountKey = storageKeys.get(0).value();

            final ObjectNode storageAccountKeyNode = mapper.createObjectNode();
            storageAccountKeyNode.put("type", "secureString");
            storageAccountKeyNode.put("defaultValue", storageAccountKey);

            // Add the storage account key
            ObjectNode.class.cast(tmp.get("parameters")).replace("storageAccountKey", storageAccountKeyNode);
        }

        ObjectNode.class.cast(tmp.get("variables")).put("vmSize", template.getVirtualMachineSize());
        // Grab the username/pass
        StandardUsernamePasswordCredentials creds = template.getVMCredentials();

        ObjectNode.class.cast(tmp.get("variables")).put("adminUsername", creds.getUsername());
        ObjectNode.class.cast(tmp.get("variables")).put("adminPassword", creds.getPassword().getPlainText());

        if (StringUtils.isNotBlank(storageAccountName)) {
            ObjectNode.class.cast(tmp.get("variables")).put("storageAccountName", storageAccountName);
        }

        if (StringUtils.isNotBlank(blobEndpointSuffix)) {
            ObjectNode.class.cast(tmp.get("variables")).put("blobEndpointSuffix", blobEndpointSuffix);
        }

        // Network properties.  If the vnet name isn't blank then
        // then subnet name can't be either (based on verification rules)
        if (StringUtils.isNotBlank(template.getVirtualNetworkName())) {
            ObjectNode.class.cast(tmp.get("variables")).put("virtualNetworkName",
                    template.getVirtualNetworkName());
            ObjectNode.class.cast(tmp.get("variables")).put("subnetName", template.getSubnetName());
        } else {
            AddDefaultVNetResourceNode(tmp, mapper);
        }

        if (!template.getUsePrivateIP()) {
            AddPublicIPResourceNode(tmp, mapper);
        }

        if (StringUtils.isNotBlank(template.getNsgName())) {
            AddNSGNode(tmp, mapper, template.getNsgName());
        }

        // Register the deployment for cleanup
        deploymentRegistrar.registerDeployment(template.getAzureCloud().name, template.getResourceGroupName(),
                deploymentName);
        // Create the deployment
        azureClient.deployments().define(deploymentName)
                .withExistingResourceGroup(template.getResourceGroupName()).withTemplate(tmp.toString())
                .withParameters("{}").withMode(DeploymentMode.INCREMENTAL).beginCreate();
        return new AzureVMDeploymentInfo(deploymentName, vmBaseName, numberOfAgents);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "AzureVMManagementServiceDelegate: deployment: Unable to deploy", e);
        // Pass the info off to the template so that it can be queued for update.
        template.handleTemplateProvisioningFailure(e.getMessage(), FailureStage.PROVISIONING);
        throw new AzureCloudException(e);
    } finally {
        if (embeddedTemplate != null)
            embeddedTemplate.close();
    }
}