Example usage for java.lang Enum valueOf

List of usage examples for java.lang Enum valueOf

Introduction

In this page you can find the example usage for java.lang Enum valueOf.

Prototype

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

Source Link

Document

Returns the enum constant of the specified enum type with the specified name.

Usage

From source file:org.kuali.kra.award.web.struts.action.AwardAction.java

/**
 * This method sets up a sponsor template synchronization loop.
 * It is called by the ui when a specific set of scopes need to by synchronized.
 * If no scopes are in the request, then a full synchronization to the scopes:
 * /*w  w w.  j a  v a2 s.com*/
 * AWARD_PAGE
 * SPONSOR_CONTACTS_TAB
 * PAYMENTS_AND_INVOICES_TAB
 * TERMS_TAB
 * REPORTS_TAB
 * COMMENTS_TAB
 * 
 * is performed. This method generates and stores the list of scopes to sync
 * and the map to indicate if confirmation is necessary from the user before
 * a particular scope is synchronized and then forwards to the method the handles
 * the request loop.
 *
 */
public ActionForward syncAwardTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    AwardForm awardForm = (AwardForm) form;
    AwardDocument awardDocument = awardForm.getAwardDocument();

    AwardTemplateSyncScope[] scopes;
    String syncScopes = getSyncScopesString(request);

    if (awardDocument.getAward().getTemplateCode() == null
            || awardDocument.getAward().getAwardTemplate() == null) {
        GlobalVariables.getMessageMap().clearErrorMessages();
        GlobalVariables.getMessageMap().putError(
                StringUtils.isBlank(syncScopes) ? "document.award.awardTemplate"
                        : String.format("document.award.awardTemplate.%s",
                                StringUtils.substring(syncScopes, 1)),
                KeyConstants.ERROR_NO_SPONSOR_TEMPLATE_FOUND, new String[] {});
        awardForm.setOldTemplateCode(null);
        awardForm.setTemplateLookup(false);
        return mapping.findForward(Constants.MAPPING_AWARD_BASIC);
    }

    Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
    if (question != null)
        return processSyncAward(mapping, awardForm, request, response);

    awardForm.setCurrentSyncScopes(null);
    awardForm.setSyncRequiresConfirmationMap(null);

    /*
     * The format for the action string is:
     * methodToCall.syncAwardTemplate:SCOPE1:...:SCOPEN].anchor...
     * Where:
     * [PropertyName|MethodName] means to sync by a property name or a method name.
     * SCOPE1...SCOPEN : A ':' delimited list of scope names that should be synced. If none are specified then the sync is done for every field and method.
     * 
     */
    if (StringUtils.isNotBlank(syncScopes) && syncScopes.length() > 1 && syncScopes.indexOf(":") > -1) {
        String[] scopeStrings = StringUtils.split(StringUtils.substringAfter(syncScopes, ":"));
        scopes = new AwardTemplateSyncScope[scopeStrings.length];
        for (int i = 0; i < scopeStrings.length; i++) {
            scopes[i] = Enum.valueOf(AwardTemplateSyncScope.class, scopeStrings[i]);
        }
        awardForm.setSyncRequiresConfirmationMap(
                generateScopeRequiresConfirmationMap(scopes, awardDocument, false, false));
        awardForm.setCurrentSyncScopes(scopes);
    } else {
        awardForm.setSyncRequiresConfirmationMap(generateScopeRequiresConfirmationMap(
                DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES, awardDocument, false, false));
        awardForm.setCurrentSyncScopes(DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES);
    }

    return processSyncAward(mapping, form, request, response);
}

From source file:org.apache.tajo.catalog.store.AbstractDBStore.java

private Type getDataType(final String typeStr) {
    try {//  w  w  w  .  j a  v  a 2 s  . c  om
        return Enum.valueOf(Type.class, typeStr);
    } catch (IllegalArgumentException iae) {
        LOG.error("Cannot find a matched type against from '" + typeStr + "'");
        return null;
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.BeanUnmarshaller.java

private <T> T unmarshalEnumFromPrimitive(PrimitiveXNode prim, Class<T> beanClass, ParsingContext pc)
        throws SchemaException {

    String primValue = (String) prim.getParsedValue(DOMUtil.XSD_STRING, String.class);
    primValue = StringUtils.trim(primValue);
    if (StringUtils.isEmpty(primValue)) {
        return null;
    }// w  w  w  . ja va2 s . c  o m

    String javaEnumString = inspector.findEnumFieldName(beanClass, primValue);
    if (javaEnumString == null) {
        for (Field field : beanClass.getDeclaredFields()) {
            if (field.getName().equals(primValue)) {
                javaEnumString = field.getName();
                break;
            }
        }
    }
    if (javaEnumString == null) {
        throw new SchemaException("Cannot find enum value for string '" + primValue + "' in " + beanClass);
    }

    @SuppressWarnings("unchecked")
    T bean = (T) Enum.valueOf((Class<Enum>) beanClass, javaEnumString);
    return bean;
}

From source file:org.gvnix.web.datatables.util.QuerydslUtils.java

/**
 * Return where clause expression for non-String
 * {@code entityPath.fieldName} by transforming it to text before check its
 * value./*from  w w  w . j  av  a2  s .com*/
 * <p/>
 * Expr:
 * {@code entityPath.fieldName.as(String.class) like ('%' + searchStr + '%')}
 * <p/>
 * Like operation is case insensitive.
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the value to find, may be null
 * @param enumClass Enumeration type. Needed to enumeration values
 * @return BooleanExpression
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> BooleanExpression createEnumExpression(PathBuilder<T> entityPath, String fieldName,
        String searchStr, Class<? extends Enum> enumClass) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    // Filter string to search than cannot be a identifier
    if (!StringUtils.isAlphanumeric(StringUtils.lowerCase(searchStr))) {
        return null;
    }

    // TODO i18n of enum name

    // normalize search string
    searchStr = StringUtils.trim(searchStr).toLowerCase();

    // locate enums matching by name
    Set matching = new HashSet();

    Enum<?> enumValue;
    String enumStr;

    for (Field enumField : enumClass.getDeclaredFields()) {
        if (enumField.isEnumConstant()) {
            enumStr = enumField.getName();
            enumValue = Enum.valueOf(enumClass, enumStr);

            // Check enum name contains string to search
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
                continue;
            }

            // Check using toString
            enumStr = enumValue.toString();
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
            }
        }
    }
    if (matching.isEmpty()) {
        return null;
    }

    // create a enum in matching condition
    BooleanExpression expression = entityPath.get(fieldName).in(matching);
    return expression;
}

From source file:com.microsoft.azure.management.websites.WebSiteOperationsImpl.java

/**
* You can create a web site by using a POST request that includes the name
* of the web site and other information in the request body.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166986.aspx for
* more information)/*from   w w  w  . j  a  va  2s  . c  o  m*/
*
* @param resourceGroupName Required. The name of the resource group.
* @param webSiteName Required. The name of the web site.
* @param slotName Optional. The name of the slot.
* @param parameters Required. Parameters supplied to the Create Web Site
* 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 URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create Web Space operation response.
*/
@Override
public WebSiteCreateResponse createOrUpdate(String resourceGroupName, String webSiteName, String slotName,
        WebSiteCreateOrUpdateParameters parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getWebSite() == null) {
        throw new NullPointerException("parameters.WebSite");
    }
    if (parameters.getWebSite().getLocation() == null) {
        throw new NullPointerException("parameters.WebSite.Location");
    }
    if (parameters.getWebSite().getProperties() != null) {
        if (parameters.getWebSite().getProperties().getServerFarm() == null) {
            throw new NullPointerException("parameters.WebSite.Properties.ServerFarm");
        }
    }

    // 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("resourceGroupName", resourceGroupName);
        tracingParameters.put("webSiteName", webSiteName);
        tracingParameters.put("slotName", slotName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createOrUpdateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Web";
    url = url + "/";
    url = url + "sites";
    url = url + "/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    if (slotName != null) {
        url = url + "/slots/" + URLEncoder.encode(slotName, "UTF-8");
    }
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-06-01");
    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
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode webSiteCreateOrUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = webSiteCreateOrUpdateParametersValue;

    if (parameters.getWebSite().getProperties() != null) {
        ObjectNode propertiesValue = objectMapper.createObjectNode();
        ((ObjectNode) webSiteCreateOrUpdateParametersValue).put("properties", propertiesValue);

        ((ObjectNode) propertiesValue).put("ServerFarm",
                parameters.getWebSite().getProperties().getServerFarm());
    }

    if (parameters.getWebSite().getId() != null) {
        ((ObjectNode) webSiteCreateOrUpdateParametersValue).put("id", parameters.getWebSite().getId());
    }

    if (parameters.getWebSite().getName() != null) {
        ((ObjectNode) webSiteCreateOrUpdateParametersValue).put("name", parameters.getWebSite().getName());
    }

    ((ObjectNode) webSiteCreateOrUpdateParametersValue).put("location", parameters.getWebSite().getLocation());

    if (parameters.getWebSite().getTags() != null) {
        ObjectNode tagsDictionary = objectMapper.createObjectNode();
        for (Map.Entry<String, String> entry : parameters.getWebSite().getTags().entrySet()) {
            String tagsKey = entry.getKey();
            String tagsValue = entry.getValue();
            ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue);
        }
        ((ObjectNode) webSiteCreateOrUpdateParametersValue).put("tags", tagsDictionary);
    }

    if (parameters.getWebSite().getType() != null) {
        ((ObjectNode) webSiteCreateOrUpdateParametersValue).put("type", parameters.getWebSite().getType());
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

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

        // Create Result
        WebSiteCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSiteCreateResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                WebSite webSiteInstance = new WebSite();
                result.setWebSite(webSiteInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    WebSiteProperties propertiesInstance = new WebSiteProperties();
                    webSiteInstance.setProperties(propertiesInstance);

                    JsonNode adminEnabledValue = propertiesValue2.get("adminEnabled");
                    if (adminEnabledValue != null && adminEnabledValue instanceof NullNode == false) {
                        boolean adminEnabledInstance;
                        adminEnabledInstance = adminEnabledValue.getBooleanValue();
                        propertiesInstance.setAdminEnabled(adminEnabledInstance);
                    }

                    JsonNode availabilityStateValue = propertiesValue2.get("availabilityState");
                    if (availabilityStateValue != null && availabilityStateValue instanceof NullNode == false) {
                        WebSpaceAvailabilityState availabilityStateInstance;
                        availabilityStateInstance = Enum.valueOf(WebSpaceAvailabilityState.class,
                                availabilityStateValue.getTextValue());
                        propertiesInstance.setAvailabilityState(availabilityStateInstance);
                    }

                    JsonNode enabledValue = propertiesValue2.get("enabled");
                    if (enabledValue != null && enabledValue instanceof NullNode == false) {
                        boolean enabledInstance;
                        enabledInstance = enabledValue.getBooleanValue();
                        propertiesInstance.setEnabled(enabledInstance);
                    }

                    JsonNode enabledHostNamesArray = propertiesValue2.get("enabledHostNames");
                    if (enabledHostNamesArray != null && enabledHostNamesArray instanceof NullNode == false) {
                        for (JsonNode enabledHostNamesValue : ((ArrayNode) enabledHostNamesArray)) {
                            propertiesInstance.getEnabledHostNames().add(enabledHostNamesValue.getTextValue());
                        }
                    }

                    JsonNode hostNameSslStatesArray = propertiesValue2.get("hostNameSslStates");
                    if (hostNameSslStatesArray != null && hostNameSslStatesArray instanceof NullNode == false) {
                        for (JsonNode hostNameSslStatesValue : ((ArrayNode) hostNameSslStatesArray)) {
                            WebSiteProperties.WebSiteHostNameSslState webSiteHostNameSslStateInstance = new WebSiteProperties.WebSiteHostNameSslState();
                            propertiesInstance.getHostNameSslStates().add(webSiteHostNameSslStateInstance);

                            JsonNode nameValue = hostNameSslStatesValue.get("name");
                            if (nameValue != null && nameValue instanceof NullNode == false) {
                                String nameInstance;
                                nameInstance = nameValue.getTextValue();
                                webSiteHostNameSslStateInstance.setName(nameInstance);
                            }

                            JsonNode sslStateValue = hostNameSslStatesValue.get("sslState");
                            if (sslStateValue != null && sslStateValue instanceof NullNode == false) {
                                WebSiteSslState sslStateInstance;
                                sslStateInstance = Enum.valueOf(WebSiteSslState.class,
                                        sslStateValue.getTextValue());
                                webSiteHostNameSslStateInstance.setSslState(sslStateInstance);
                            }

                            JsonNode thumbprintValue = hostNameSslStatesValue.get("thumbprint");
                            if (thumbprintValue != null && thumbprintValue instanceof NullNode == false) {
                                String thumbprintInstance;
                                thumbprintInstance = thumbprintValue.getTextValue();
                                webSiteHostNameSslStateInstance.setThumbprint(thumbprintInstance);
                            }

                            JsonNode virtualIPValue = hostNameSslStatesValue.get("virtualIP");
                            if (virtualIPValue != null && virtualIPValue instanceof NullNode == false) {
                                InetAddress virtualIPInstance;
                                virtualIPInstance = InetAddress.getByName(virtualIPValue.getTextValue());
                                webSiteHostNameSslStateInstance.setVirtualIP(virtualIPInstance);
                            }

                            JsonNode ipBasedSslResultValue = hostNameSslStatesValue.get("ipBasedSslResult");
                            if (ipBasedSslResultValue != null
                                    && ipBasedSslResultValue instanceof NullNode == false) {
                                String ipBasedSslResultInstance;
                                ipBasedSslResultInstance = ipBasedSslResultValue.getTextValue();
                                webSiteHostNameSslStateInstance.setIpBasedSslResult(ipBasedSslResultInstance);
                            }

                            JsonNode toUpdateValue = hostNameSslStatesValue.get("toUpdate");
                            if (toUpdateValue != null && toUpdateValue instanceof NullNode == false) {
                                boolean toUpdateInstance;
                                toUpdateInstance = toUpdateValue.getBooleanValue();
                                webSiteHostNameSslStateInstance.setToUpdate(toUpdateInstance);
                            }

                            JsonNode toUpdateIpBasedSslValue = hostNameSslStatesValue.get("toUpdateIpBasedSsl");
                            if (toUpdateIpBasedSslValue != null
                                    && toUpdateIpBasedSslValue instanceof NullNode == false) {
                                boolean toUpdateIpBasedSslInstance;
                                toUpdateIpBasedSslInstance = toUpdateIpBasedSslValue.getBooleanValue();
                                webSiteHostNameSslStateInstance
                                        .setToUpdateIpBasedSsl(toUpdateIpBasedSslInstance);
                            }

                            JsonNode hostTypeValue = hostNameSslStatesValue.get("hostType");
                            if (hostTypeValue != null && hostTypeValue instanceof NullNode == false) {
                                HostType hostTypeInstance;
                                hostTypeInstance = Enum.valueOf(HostType.class, hostTypeValue.getTextValue());
                                webSiteHostNameSslStateInstance.setHostType(hostTypeInstance);
                            }
                        }
                    }

                    JsonNode hostNamesArray = propertiesValue2.get("hostNames");
                    if (hostNamesArray != null && hostNamesArray instanceof NullNode == false) {
                        for (JsonNode hostNamesValue : ((ArrayNode) hostNamesArray)) {
                            propertiesInstance.getHostNames().add(hostNamesValue.getTextValue());
                        }
                    }

                    JsonNode lastModifiedTimeUtcValue = propertiesValue2.get("lastModifiedTimeUtc");
                    if (lastModifiedTimeUtcValue != null
                            && lastModifiedTimeUtcValue instanceof NullNode == false) {
                        Calendar lastModifiedTimeUtcInstance;
                        lastModifiedTimeUtcInstance = DatatypeConverter
                                .parseDateTime(lastModifiedTimeUtcValue.getTextValue());
                        propertiesInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance);
                    }

                    JsonNode repositorySiteNameValue = propertiesValue2.get("repositorySiteName");
                    if (repositorySiteNameValue != null
                            && repositorySiteNameValue instanceof NullNode == false) {
                        String repositorySiteNameInstance;
                        repositorySiteNameInstance = repositorySiteNameValue.getTextValue();
                        propertiesInstance.setRepositorySiteName(repositorySiteNameInstance);
                    }

                    JsonNode runtimeAvailabilityStateValue = propertiesValue2.get("runtimeAvailabilityState");
                    if (runtimeAvailabilityStateValue != null
                            && runtimeAvailabilityStateValue instanceof NullNode == false) {
                        WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance;
                        runtimeAvailabilityStateInstance = Enum.valueOf(WebSiteRuntimeAvailabilityState.class,
                                runtimeAvailabilityStateValue.getTextValue());
                        propertiesInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance);
                    }

                    JsonNode trafficManagerHostNamesArray = propertiesValue2.get("trafficManagerHostNames");
                    if (trafficManagerHostNamesArray != null
                            && trafficManagerHostNamesArray instanceof NullNode == false) {
                        for (JsonNode trafficManagerHostNamesValue : ((ArrayNode) trafficManagerHostNamesArray)) {
                            propertiesInstance.getTrafficManagerHostNames()
                                    .add(trafficManagerHostNamesValue.getTextValue());
                        }
                    }

                    JsonNode selfLinkValue = propertiesValue2.get("selfLink");
                    if (selfLinkValue != null && selfLinkValue instanceof NullNode == false) {
                        URI selfLinkInstance;
                        selfLinkInstance = new URI(selfLinkValue.getTextValue());
                        propertiesInstance.setUri(selfLinkInstance);
                    }

                    JsonNode serverFarmValue = propertiesValue2.get("serverFarm");
                    if (serverFarmValue != null && serverFarmValue instanceof NullNode == false) {
                        String serverFarmInstance;
                        serverFarmInstance = serverFarmValue.getTextValue();
                        propertiesInstance.setServerFarm(serverFarmInstance);
                    }

                    JsonNode serverFarmIdValue = propertiesValue2.get("serverFarmId");
                    if (serverFarmIdValue != null && serverFarmIdValue instanceof NullNode == false) {
                        String serverFarmIdInstance;
                        serverFarmIdInstance = serverFarmIdValue.getTextValue();
                        propertiesInstance.setServerFarmId(serverFarmIdInstance);
                    }

                    JsonNode skuValue = propertiesValue2.get("sku");
                    if (skuValue != null && skuValue instanceof NullNode == false) {
                        SkuOptions skuInstance;
                        skuInstance = Enum.valueOf(SkuOptions.class, skuValue.getTextValue());
                        propertiesInstance.setSku(skuInstance);
                    }

                    JsonNode sitePropertiesValue = propertiesValue2.get("siteProperties");
                    if (sitePropertiesValue != null && sitePropertiesValue instanceof NullNode == false) {
                        WebSiteProperties.SiteProperties sitePropertiesInstance = new WebSiteProperties.SiteProperties();
                        propertiesInstance.setProperties(sitePropertiesInstance);

                        JsonNode appSettingsSequenceElement = ((JsonNode) sitePropertiesValue
                                .get("appSettings"));
                        if (appSettingsSequenceElement != null
                                && appSettingsSequenceElement instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr = appSettingsSequenceElement.getFields();
                            while (itr.hasNext()) {
                                Map.Entry<String, JsonNode> property = itr.next();
                                String appSettingsKey = property.getKey();
                                String appSettingsValue = property.getValue().getTextValue();
                                sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue);
                            }
                        }

                        JsonNode metadataSequenceElement = ((JsonNode) sitePropertiesValue.get("metadata"));
                        if (metadataSequenceElement != null
                                && metadataSequenceElement instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr2 = metadataSequenceElement.getFields();
                            while (itr2.hasNext()) {
                                Map.Entry<String, JsonNode> property2 = itr2.next();
                                String metadataKey = property2.getKey();
                                String metadataValue = property2.getValue().getTextValue();
                                sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue);
                            }
                        }

                        JsonNode propertiesSequenceElement = ((JsonNode) sitePropertiesValue.get("properties"));
                        if (propertiesSequenceElement != null
                                && propertiesSequenceElement instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr3 = propertiesSequenceElement.getFields();
                            while (itr3.hasNext()) {
                                Map.Entry<String, JsonNode> property3 = itr3.next();
                                String propertiesKey = property3.getKey();
                                String propertiesValue3 = property3.getValue().getTextValue();
                                sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue3);
                            }
                        }
                    }

                    JsonNode siteConfigValue = propertiesValue2.get("siteConfig");
                    if (siteConfigValue != null && siteConfigValue instanceof NullNode == false) {
                        WebSiteConfiguration siteConfigInstance = new WebSiteConfiguration();
                        propertiesInstance.setSiteConfig(siteConfigInstance);

                        JsonNode appSettingsSequenceElement2 = ((JsonNode) siteConfigValue.get("appSettings"));
                        if (appSettingsSequenceElement2 != null
                                && appSettingsSequenceElement2 instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr4 = appSettingsSequenceElement2
                                    .getFields();
                            while (itr4.hasNext()) {
                                Map.Entry<String, JsonNode> property4 = itr4.next();
                                String appSettingsKey2 = property4.getKey();
                                String appSettingsValue2 = property4.getValue().getTextValue();
                                siteConfigInstance.getAppSettings().put(appSettingsKey2, appSettingsValue2);
                            }
                        }

                        JsonNode connectionStringsArray = siteConfigValue.get("connectionStrings");
                        if (connectionStringsArray != null
                                && connectionStringsArray instanceof NullNode == false) {
                            for (JsonNode connectionStringsValue : ((ArrayNode) connectionStringsArray)) {
                                ConnectionStringInfo connStringInfoInstance = new ConnectionStringInfo();
                                siteConfigInstance.getConnectionStrings().add(connStringInfoInstance);

                                JsonNode connectionStringValue = connectionStringsValue.get("connectionString");
                                if (connectionStringValue != null
                                        && connectionStringValue instanceof NullNode == false) {
                                    String connectionStringInstance;
                                    connectionStringInstance = connectionStringValue.getTextValue();
                                    connStringInfoInstance.setConnectionString(connectionStringInstance);
                                }

                                JsonNode nameValue2 = connectionStringsValue.get("name");
                                if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                                    String nameInstance2;
                                    nameInstance2 = nameValue2.getTextValue();
                                    connStringInfoInstance.setName(nameInstance2);
                                }

                                JsonNode typeValue = connectionStringsValue.get("type");
                                if (typeValue != null && typeValue instanceof NullNode == false) {
                                    DatabaseServerType typeInstance;
                                    typeInstance = Enum.valueOf(DatabaseServerType.class,
                                            typeValue.getTextValue());
                                    connStringInfoInstance.setType(typeInstance);
                                }
                            }
                        }

                        JsonNode defaultDocumentsArray = siteConfigValue.get("defaultDocuments");
                        if (defaultDocumentsArray != null
                                && defaultDocumentsArray instanceof NullNode == false) {
                            for (JsonNode defaultDocumentsValue : ((ArrayNode) defaultDocumentsArray)) {
                                siteConfigInstance.getDefaultDocuments()
                                        .add(defaultDocumentsValue.getTextValue());
                            }
                        }

                        JsonNode detailedErrorLoggingEnabledValue = siteConfigValue
                                .get("detailedErrorLoggingEnabled");
                        if (detailedErrorLoggingEnabledValue != null
                                && detailedErrorLoggingEnabledValue instanceof NullNode == false) {
                            boolean detailedErrorLoggingEnabledInstance;
                            detailedErrorLoggingEnabledInstance = detailedErrorLoggingEnabledValue
                                    .getBooleanValue();
                            siteConfigInstance
                                    .setDetailedErrorLoggingEnabled(detailedErrorLoggingEnabledInstance);
                        }

                        JsonNode documentRootValue = siteConfigValue.get("documentRoot");
                        if (documentRootValue != null && documentRootValue instanceof NullNode == false) {
                            String documentRootInstance;
                            documentRootInstance = documentRootValue.getTextValue();
                            siteConfigInstance.setDocumentRoot(documentRootInstance);
                        }

                        JsonNode handlerMappingsArray = siteConfigValue.get("handlerMappings");
                        if (handlerMappingsArray != null && handlerMappingsArray instanceof NullNode == false) {
                            for (JsonNode handlerMappingsValue : ((ArrayNode) handlerMappingsArray)) {
                                WebSiteConfiguration.HandlerMapping handlerMappingInstance = new WebSiteConfiguration.HandlerMapping();
                                siteConfigInstance.getHandlerMappings().add(handlerMappingInstance);

                                JsonNode argumentsValue = handlerMappingsValue.get("arguments");
                                if (argumentsValue != null && argumentsValue instanceof NullNode == false) {
                                    String argumentsInstance;
                                    argumentsInstance = argumentsValue.getTextValue();
                                    handlerMappingInstance.setArguments(argumentsInstance);
                                }

                                JsonNode extensionValue = handlerMappingsValue.get("extension");
                                if (extensionValue != null && extensionValue instanceof NullNode == false) {
                                    String extensionInstance;
                                    extensionInstance = extensionValue.getTextValue();
                                    handlerMappingInstance.setExtension(extensionInstance);
                                }

                                JsonNode scriptProcessorValue = handlerMappingsValue.get("scriptProcessor");
                                if (scriptProcessorValue != null
                                        && scriptProcessorValue instanceof NullNode == false) {
                                    String scriptProcessorInstance;
                                    scriptProcessorInstance = scriptProcessorValue.getTextValue();
                                    handlerMappingInstance.setScriptProcessor(scriptProcessorInstance);
                                }
                            }
                        }

                        JsonNode httpLoggingEnabledValue = siteConfigValue.get("httpLoggingEnabled");
                        if (httpLoggingEnabledValue != null
                                && httpLoggingEnabledValue instanceof NullNode == false) {
                            boolean httpLoggingEnabledInstance;
                            httpLoggingEnabledInstance = httpLoggingEnabledValue.getBooleanValue();
                            siteConfigInstance.setHttpLoggingEnabled(httpLoggingEnabledInstance);
                        }

                        JsonNode logsDirectorySizeLimitValue = siteConfigValue.get("logsDirectorySizeLimit");
                        if (logsDirectorySizeLimitValue != null
                                && logsDirectorySizeLimitValue instanceof NullNode == false) {
                            int logsDirectorySizeLimitInstance;
                            logsDirectorySizeLimitInstance = logsDirectorySizeLimitValue.getIntValue();
                            siteConfigInstance.setLogsDirectorySizeLimit(logsDirectorySizeLimitInstance);
                        }

                        JsonNode managedPipelineModeValue = siteConfigValue.get("managedPipelineMode");
                        if (managedPipelineModeValue != null
                                && managedPipelineModeValue instanceof NullNode == false) {
                            ManagedPipelineMode managedPipelineModeInstance;
                            managedPipelineModeInstance = Enum.valueOf(ManagedPipelineMode.class,
                                    managedPipelineModeValue.getTextValue());
                            siteConfigInstance.setManagedPipelineMode(managedPipelineModeInstance);
                        }

                        JsonNode metadataSequenceElement2 = ((JsonNode) siteConfigValue.get("metadata"));
                        if (metadataSequenceElement2 != null
                                && metadataSequenceElement2 instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr5 = metadataSequenceElement2.getFields();
                            while (itr5.hasNext()) {
                                Map.Entry<String, JsonNode> property5 = itr5.next();
                                String metadataKey2 = property5.getKey();
                                String metadataValue2 = property5.getValue().getTextValue();
                                siteConfigInstance.getMetadata().put(metadataKey2, metadataValue2);
                            }
                        }

                        JsonNode netFrameworkVersionValue = siteConfigValue.get("netFrameworkVersion");
                        if (netFrameworkVersionValue != null
                                && netFrameworkVersionValue instanceof NullNode == false) {
                            String netFrameworkVersionInstance;
                            netFrameworkVersionInstance = netFrameworkVersionValue.getTextValue();
                            siteConfigInstance.setNetFrameworkVersion(netFrameworkVersionInstance);
                        }

                        JsonNode numberOfWorkersValue = siteConfigValue.get("numberOfWorkers");
                        if (numberOfWorkersValue != null && numberOfWorkersValue instanceof NullNode == false) {
                            int numberOfWorkersInstance;
                            numberOfWorkersInstance = numberOfWorkersValue.getIntValue();
                            siteConfigInstance.setNumberOfWorkers(numberOfWorkersInstance);
                        }

                        JsonNode phpVersionValue = siteConfigValue.get("phpVersion");
                        if (phpVersionValue != null && phpVersionValue instanceof NullNode == false) {
                            String phpVersionInstance;
                            phpVersionInstance = phpVersionValue.getTextValue();
                            siteConfigInstance.setPhpVersion(phpVersionInstance);
                        }

                        JsonNode pythonVersionValue = siteConfigValue.get("pythonVersion");
                        if (pythonVersionValue != null && pythonVersionValue instanceof NullNode == false) {
                            String pythonVersionInstance;
                            pythonVersionInstance = pythonVersionValue.getTextValue();
                            siteConfigInstance.setPythonVersion(pythonVersionInstance);
                        }

                        JsonNode publishingPasswordValue = siteConfigValue.get("publishingPassword");
                        if (publishingPasswordValue != null
                                && publishingPasswordValue instanceof NullNode == false) {
                            String publishingPasswordInstance;
                            publishingPasswordInstance = publishingPasswordValue.getTextValue();
                            siteConfigInstance.setPublishingPassword(publishingPasswordInstance);
                        }

                        JsonNode publishingUsernameValue = siteConfigValue.get("publishingUsername");
                        if (publishingUsernameValue != null
                                && publishingUsernameValue instanceof NullNode == false) {
                            String publishingUsernameInstance;
                            publishingUsernameInstance = publishingUsernameValue.getTextValue();
                            siteConfigInstance.setPublishingUserName(publishingUsernameInstance);
                        }

                        JsonNode remoteDebuggingEnabledValue = siteConfigValue.get("RemoteDebuggingEnabled");
                        if (remoteDebuggingEnabledValue != null
                                && remoteDebuggingEnabledValue instanceof NullNode == false) {
                            boolean remoteDebuggingEnabledInstance;
                            remoteDebuggingEnabledInstance = remoteDebuggingEnabledValue.getBooleanValue();
                            siteConfigInstance.setRemoteDebuggingEnabled(remoteDebuggingEnabledInstance);
                        }

                        JsonNode remoteDebuggingVersionValue = siteConfigValue.get("remoteDebuggingVersion");
                        if (remoteDebuggingVersionValue != null
                                && remoteDebuggingVersionValue instanceof NullNode == false) {
                            RemoteDebuggingVersion remoteDebuggingVersionInstance;
                            remoteDebuggingVersionInstance = Enum.valueOf(RemoteDebuggingVersion.class,
                                    remoteDebuggingVersionValue.getTextValue());
                            siteConfigInstance.setRemoteDebuggingVersion(remoteDebuggingVersionInstance);
                        }

                        JsonNode requestTracingEnabledValue = siteConfigValue.get("requestTracingEnabled");
                        if (requestTracingEnabledValue != null
                                && requestTracingEnabledValue instanceof NullNode == false) {
                            boolean requestTracingEnabledInstance;
                            requestTracingEnabledInstance = requestTracingEnabledValue.getBooleanValue();
                            siteConfigInstance.setRequestTracingEnabled(requestTracingEnabledInstance);
                        }

                        JsonNode requestTracingExpirationTimeValue = siteConfigValue
                                .get("requestTracingExpirationTime");
                        if (requestTracingExpirationTimeValue != null
                                && requestTracingExpirationTimeValue instanceof NullNode == false) {
                            Calendar requestTracingExpirationTimeInstance;
                            requestTracingExpirationTimeInstance = DatatypeConverter
                                    .parseDateTime(requestTracingExpirationTimeValue.getTextValue());
                            siteConfigInstance
                                    .setRequestTracingExpirationTime(requestTracingExpirationTimeInstance);
                        }

                        JsonNode scmTypeValue = siteConfigValue.get("scmType");
                        if (scmTypeValue != null && scmTypeValue instanceof NullNode == false) {
                            String scmTypeInstance;
                            scmTypeInstance = scmTypeValue.getTextValue();
                            siteConfigInstance.setScmType(scmTypeInstance);
                        }

                        JsonNode autoSwapSlotNameValue = siteConfigValue.get("autoSwapSlotName");
                        if (autoSwapSlotNameValue != null
                                && autoSwapSlotNameValue instanceof NullNode == false) {
                            String autoSwapSlotNameInstance;
                            autoSwapSlotNameInstance = autoSwapSlotNameValue.getTextValue();
                            siteConfigInstance.setAutoSwapSlotName(autoSwapSlotNameInstance);
                        }

                        JsonNode use32BitWorkerProcessValue = siteConfigValue.get("use32BitWorkerProcess");
                        if (use32BitWorkerProcessValue != null
                                && use32BitWorkerProcessValue instanceof NullNode == false) {
                            boolean use32BitWorkerProcessInstance;
                            use32BitWorkerProcessInstance = use32BitWorkerProcessValue.getBooleanValue();
                            siteConfigInstance.setUse32BitWorkerProcess(use32BitWorkerProcessInstance);
                        }

                        JsonNode webSocketsEnabledValue = siteConfigValue.get("webSocketsEnabled");
                        if (webSocketsEnabledValue != null
                                && webSocketsEnabledValue instanceof NullNode == false) {
                            boolean webSocketsEnabledInstance;
                            webSocketsEnabledInstance = webSocketsEnabledValue.getBooleanValue();
                            siteConfigInstance.setWebSocketsEnabled(webSocketsEnabledInstance);
                        }

                        JsonNode limitsValue = siteConfigValue.get("limits");
                        if (limitsValue != null && limitsValue instanceof NullNode == false) {
                            SiteLimits limitsInstance = new SiteLimits();
                            siteConfigInstance.setLimits(limitsInstance);

                            JsonNode maxPercentageCpuValue = limitsValue.get("maxPercentageCpu");
                            if (maxPercentageCpuValue != null
                                    && maxPercentageCpuValue instanceof NullNode == false) {
                                double maxPercentageCpuInstance;
                                maxPercentageCpuInstance = maxPercentageCpuValue.getDoubleValue();
                                limitsInstance.setMaxPercentageCpu(maxPercentageCpuInstance);
                            }

                            JsonNode maxMemoryInMbValue = limitsValue.get("maxMemoryInMb");
                            if (maxMemoryInMbValue != null && maxMemoryInMbValue instanceof NullNode == false) {
                                long maxMemoryInMbInstance;
                                maxMemoryInMbInstance = maxMemoryInMbValue.getLongValue();
                                limitsInstance.setMaxMemoryInMb(maxMemoryInMbInstance);
                            }

                            JsonNode maxDiskSizeInMbValue = limitsValue.get("maxDiskSizeInMb");
                            if (maxDiskSizeInMbValue != null
                                    && maxDiskSizeInMbValue instanceof NullNode == false) {
                                long maxDiskSizeInMbInstance;
                                maxDiskSizeInMbInstance = maxDiskSizeInMbValue.getLongValue();
                                limitsInstance.setMaxDiskSizeInMb(maxDiskSizeInMbInstance);
                            }
                        }
                    }

                    JsonNode stateValue = propertiesValue2.get("state");
                    if (stateValue != null && stateValue instanceof NullNode == false) {
                        WebSiteState stateInstance;
                        stateInstance = Enum.valueOf(WebSiteState.class, stateValue.getTextValue());
                        propertiesInstance.setState(stateInstance);
                    }

                    JsonNode usageStateValue = propertiesValue2.get("usageState");
                    if (usageStateValue != null && usageStateValue instanceof NullNode == false) {
                        WebSiteUsageState usageStateInstance;
                        usageStateInstance = Enum.valueOf(WebSiteUsageState.class,
                                usageStateValue.getTextValue());
                        propertiesInstance.setUsageState(usageStateInstance);
                    }

                    JsonNode webSpaceValue = propertiesValue2.get("webSpace");
                    if (webSpaceValue != null && webSpaceValue instanceof NullNode == false) {
                        String webSpaceInstance;
                        webSpaceInstance = webSpaceValue.getTextValue();
                        propertiesInstance.setWebSpace(webSpaceInstance);
                    }

                    JsonNode provisioningStateValue = propertiesValue2.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        propertiesInstance.setProvisioningState(provisioningStateInstance);
                    }
                }

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    webSiteInstance.setId(idInstance);
                }

                JsonNode nameValue3 = responseDoc.get("name");
                if (nameValue3 != null && nameValue3 instanceof NullNode == false) {
                    String nameInstance3;
                    nameInstance3 = nameValue3.getTextValue();
                    webSiteInstance.setName(nameInstance3);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    webSiteInstance.setLocation(locationInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr6 = tagsSequenceElement.getFields();
                    while (itr6.hasNext()) {
                        Map.Entry<String, JsonNode> property6 = itr6.next();
                        String tagsKey2 = property6.getKey();
                        String tagsValue2 = property6.getValue().getTextValue();
                        webSiteInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }

                JsonNode typeValue2 = responseDoc.get("type");
                if (typeValue2 != null && typeValue2 instanceof NullNode == false) {
                    String typeInstance2;
                    typeInstance2 = typeValue2.getTextValue();
                    webSiteInstance.setType(typeInstance2);
                }
            }

        }
        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:ai.aitia.meme.paramsweep.intellisweepPlugin.JgapGAPlugin.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object parseListElement(final Class<?> type, final String strValue) throws WizardLoadingException {
    if (String.class.equals(type)) {
        return strValue;
    }//w  w w .j  a  va  2 s.  com

    if (Enum.class.isAssignableFrom(type)) {
        final Class<? extends Enum> clazz = (Class<? extends Enum>) type;
        return Enum.valueOf(clazz, strValue);
    }

    if (type.equals(Double.class) || type.equals(Float.class) || type.equals(Double.TYPE)
            || type.equals(Float.TYPE)) {
        try {
            return Double.parseDouble(strValue);
        } catch (final NumberFormatException e) {
            throw new WizardLoadingException(true,
                    "invalid content (" + strValue + ") at node: " + LIST_VALUE + " (expected: real number)");
        }
    }

    try {
        return Long.parseLong(strValue);
    } catch (final NumberFormatException e) {
        throw new WizardLoadingException(true,
                "invalid content (" + strValue + ") at node: " + LIST_VALUE + " (expected: integer number)");
    }
}

From source file:com.microsoft.azure.management.resources.DeploymentOperationsImpl.java

/**
* Get a deployment./*from   w ww.  j  a v  a 2  s  .  c  o  m*/
*
* @param resourceGroupName Required. The name of the resource group to get.
* The name is case insensitive.
* @param deploymentName Required. The name of the deployment.
* @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 Template deployment information.
*/
@Override
public DeploymentGetResult get(String resourceGroupName, String deploymentName)
        throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (resourceGroupName != null && resourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourcegroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01-preview");
    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("Content-Type", "application/json; charset=utf-8");

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

        // Create Result
        DeploymentGetResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DeploymentGetResult();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                DeploymentExtended deploymentInstance = new DeploymentExtended();
                result.setDeployment(deploymentInstance);

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    deploymentInstance.setId(idInstance);
                }

                JsonNode nameValue = responseDoc.get("name");
                if (nameValue != null && nameValue instanceof NullNode == false) {
                    String nameInstance;
                    nameInstance = nameValue.getTextValue();
                    deploymentInstance.setName(nameInstance);
                }

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    DeploymentPropertiesExtended propertiesInstance = new DeploymentPropertiesExtended();
                    deploymentInstance.setProperties(propertiesInstance);

                    JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        propertiesInstance.setProvisioningState(provisioningStateInstance);
                    }

                    JsonNode correlationIdValue = propertiesValue.get("correlationId");
                    if (correlationIdValue != null && correlationIdValue instanceof NullNode == false) {
                        String correlationIdInstance;
                        correlationIdInstance = correlationIdValue.getTextValue();
                        propertiesInstance.setCorrelationId(correlationIdInstance);
                    }

                    JsonNode timestampValue = propertiesValue.get("timestamp");
                    if (timestampValue != null && timestampValue instanceof NullNode == false) {
                        Calendar timestampInstance;
                        timestampInstance = DatatypeConverter.parseDateTime(timestampValue.getTextValue());
                        propertiesInstance.setTimestamp(timestampInstance);
                    }

                    JsonNode outputsValue = propertiesValue.get("outputs");
                    if (outputsValue != null && outputsValue instanceof NullNode == false) {
                        String outputsInstance;
                        outputsInstance = outputsValue.getTextValue();
                        propertiesInstance.setOutputs(outputsInstance);
                    }

                    JsonNode providersArray = propertiesValue.get("providers");
                    if (providersArray != null && providersArray instanceof NullNode == false) {
                        for (JsonNode providersValue : ((ArrayNode) providersArray)) {
                            Provider providerInstance = new Provider();
                            propertiesInstance.getProviders().add(providerInstance);

                            JsonNode idValue2 = providersValue.get("id");
                            if (idValue2 != null && idValue2 instanceof NullNode == false) {
                                String idInstance2;
                                idInstance2 = idValue2.getTextValue();
                                providerInstance.setId(idInstance2);
                            }

                            JsonNode namespaceValue = providersValue.get("namespace");
                            if (namespaceValue != null && namespaceValue instanceof NullNode == false) {
                                String namespaceInstance;
                                namespaceInstance = namespaceValue.getTextValue();
                                providerInstance.setNamespace(namespaceInstance);
                            }

                            JsonNode registrationStateValue = providersValue.get("registrationState");
                            if (registrationStateValue != null
                                    && registrationStateValue instanceof NullNode == false) {
                                String registrationStateInstance;
                                registrationStateInstance = registrationStateValue.getTextValue();
                                providerInstance.setRegistrationState(registrationStateInstance);
                            }

                            JsonNode resourceTypesArray = providersValue.get("resourceTypes");
                            if (resourceTypesArray != null && resourceTypesArray instanceof NullNode == false) {
                                for (JsonNode resourceTypesValue : ((ArrayNode) resourceTypesArray)) {
                                    ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                    providerInstance.getResourceTypes().add(providerResourceTypeInstance);

                                    JsonNode resourceTypeValue = resourceTypesValue.get("resourceType");
                                    if (resourceTypeValue != null
                                            && resourceTypeValue instanceof NullNode == false) {
                                        String resourceTypeInstance;
                                        resourceTypeInstance = resourceTypeValue.getTextValue();
                                        providerResourceTypeInstance.setName(resourceTypeInstance);
                                    }

                                    JsonNode locationsArray = resourceTypesValue.get("locations");
                                    if (locationsArray != null && locationsArray instanceof NullNode == false) {
                                        for (JsonNode locationsValue : ((ArrayNode) locationsArray)) {
                                            providerResourceTypeInstance.getLocations()
                                                    .add(locationsValue.getTextValue());
                                        }
                                    }

                                    JsonNode apiVersionsArray = resourceTypesValue.get("apiVersions");
                                    if (apiVersionsArray != null
                                            && apiVersionsArray instanceof NullNode == false) {
                                        for (JsonNode apiVersionsValue : ((ArrayNode) apiVersionsArray)) {
                                            providerResourceTypeInstance.getApiVersions()
                                                    .add(apiVersionsValue.getTextValue());
                                        }
                                    }

                                    JsonNode propertiesSequenceElement = ((JsonNode) resourceTypesValue
                                            .get("properties"));
                                    if (propertiesSequenceElement != null
                                            && propertiesSequenceElement instanceof NullNode == false) {
                                        Iterator<Map.Entry<String, JsonNode>> itr = propertiesSequenceElement
                                                .getFields();
                                        while (itr.hasNext()) {
                                            Map.Entry<String, JsonNode> property = itr.next();
                                            String propertiesKey = property.getKey();
                                            String propertiesValue2 = property.getValue().getTextValue();
                                            providerResourceTypeInstance.getProperties().put(propertiesKey,
                                                    propertiesValue2);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    JsonNode dependenciesArray = propertiesValue.get("dependencies");
                    if (dependenciesArray != null && dependenciesArray instanceof NullNode == false) {
                        for (JsonNode dependenciesValue : ((ArrayNode) dependenciesArray)) {
                            Dependency dependencyInstance = new Dependency();
                            propertiesInstance.getDependencies().add(dependencyInstance);

                            JsonNode dependsOnArray = dependenciesValue.get("dependsOn");
                            if (dependsOnArray != null && dependsOnArray instanceof NullNode == false) {
                                for (JsonNode dependsOnValue : ((ArrayNode) dependsOnArray)) {
                                    BasicDependency basicDependencyInstance = new BasicDependency();
                                    dependencyInstance.getDependsOn().add(basicDependencyInstance);

                                    JsonNode idValue3 = dependsOnValue.get("id");
                                    if (idValue3 != null && idValue3 instanceof NullNode == false) {
                                        String idInstance3;
                                        idInstance3 = idValue3.getTextValue();
                                        basicDependencyInstance.setId(idInstance3);
                                    }

                                    JsonNode resourceTypeValue2 = dependsOnValue.get("resourceType");
                                    if (resourceTypeValue2 != null
                                            && resourceTypeValue2 instanceof NullNode == false) {
                                        String resourceTypeInstance2;
                                        resourceTypeInstance2 = resourceTypeValue2.getTextValue();
                                        basicDependencyInstance.setResourceType(resourceTypeInstance2);
                                    }

                                    JsonNode resourceNameValue = dependsOnValue.get("resourceName");
                                    if (resourceNameValue != null
                                            && resourceNameValue instanceof NullNode == false) {
                                        String resourceNameInstance;
                                        resourceNameInstance = resourceNameValue.getTextValue();
                                        basicDependencyInstance.setResourceName(resourceNameInstance);
                                    }
                                }
                            }

                            JsonNode idValue4 = dependenciesValue.get("id");
                            if (idValue4 != null && idValue4 instanceof NullNode == false) {
                                String idInstance4;
                                idInstance4 = idValue4.getTextValue();
                                dependencyInstance.setId(idInstance4);
                            }

                            JsonNode resourceTypeValue3 = dependenciesValue.get("resourceType");
                            if (resourceTypeValue3 != null && resourceTypeValue3 instanceof NullNode == false) {
                                String resourceTypeInstance3;
                                resourceTypeInstance3 = resourceTypeValue3.getTextValue();
                                dependencyInstance.setResourceType(resourceTypeInstance3);
                            }

                            JsonNode resourceNameValue2 = dependenciesValue.get("resourceName");
                            if (resourceNameValue2 != null && resourceNameValue2 instanceof NullNode == false) {
                                String resourceNameInstance2;
                                resourceNameInstance2 = resourceNameValue2.getTextValue();
                                dependencyInstance.setResourceName(resourceNameInstance2);
                            }
                        }
                    }

                    JsonNode templateValue = propertiesValue.get("template");
                    if (templateValue != null && templateValue instanceof NullNode == false) {
                        String templateInstance;
                        templateInstance = templateValue.getTextValue();
                        propertiesInstance.setTemplate(templateInstance);
                    }

                    JsonNode templateLinkValue = propertiesValue.get("templateLink");
                    if (templateLinkValue != null && templateLinkValue instanceof NullNode == false) {
                        TemplateLink templateLinkInstance = new TemplateLink();
                        propertiesInstance.setTemplateLink(templateLinkInstance);

                        JsonNode uriValue = templateLinkValue.get("uri");
                        if (uriValue != null && uriValue instanceof NullNode == false) {
                            URI uriInstance;
                            uriInstance = new URI(uriValue.getTextValue());
                            templateLinkInstance.setUri(uriInstance);
                        }

                        JsonNode contentVersionValue = templateLinkValue.get("contentVersion");
                        if (contentVersionValue != null && contentVersionValue instanceof NullNode == false) {
                            String contentVersionInstance;
                            contentVersionInstance = contentVersionValue.getTextValue();
                            templateLinkInstance.setContentVersion(contentVersionInstance);
                        }
                    }

                    JsonNode parametersValue = propertiesValue.get("parameters");
                    if (parametersValue != null && parametersValue instanceof NullNode == false) {
                        String parametersInstance;
                        parametersInstance = parametersValue.getTextValue();
                        propertiesInstance.setParameters(parametersInstance);
                    }

                    JsonNode parametersLinkValue = propertiesValue.get("parametersLink");
                    if (parametersLinkValue != null && parametersLinkValue instanceof NullNode == false) {
                        ParametersLink parametersLinkInstance = new ParametersLink();
                        propertiesInstance.setParametersLink(parametersLinkInstance);

                        JsonNode uriValue2 = parametersLinkValue.get("uri");
                        if (uriValue2 != null && uriValue2 instanceof NullNode == false) {
                            URI uriInstance2;
                            uriInstance2 = new URI(uriValue2.getTextValue());
                            parametersLinkInstance.setUri(uriInstance2);
                        }

                        JsonNode contentVersionValue2 = parametersLinkValue.get("contentVersion");
                        if (contentVersionValue2 != null && contentVersionValue2 instanceof NullNode == false) {
                            String contentVersionInstance2;
                            contentVersionInstance2 = contentVersionValue2.getTextValue();
                            parametersLinkInstance.setContentVersion(contentVersionInstance2);
                        }
                    }

                    JsonNode modeValue = propertiesValue.get("mode");
                    if (modeValue != null && modeValue instanceof NullNode == false) {
                        DeploymentMode modeInstance;
                        modeInstance = Enum.valueOf(DeploymentMode.class, modeValue.getTextValue());
                        propertiesInstance.setMode(modeInstance);
                    }
                }
            }

        }
        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.azure.management.notificationhubs.NotificationHubOperationsImpl.java

/**
* The create NotificationHub authorization rule operation creates an
* authorization rule for a NotificationHub
*
* @param resourceGroupName Required. The name of the resource group.
* @param namespaceName Required. The namespace name.
* @param notificationHubName Required. The notification hub name.
* @param authorizationRuleName Required. The namespace
* authorizationRuleName name.//from   w  w w  .  j a v  a 2s  .c o m
* @param parameters Required. The shared access authorization rule.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Response of the CreateOrUpdate operation on the AuthorizationRules
*/
@Override
public SharedAccessAuthorizationRuleCreateOrUpdateResponse createOrUpdateAuthorizationRule(
        String resourceGroupName, String namespaceName, String notificationHubName,
        String authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (notificationHubName == null) {
        throw new NullPointerException("notificationHubName");
    }
    if (authorizationRuleName == null) {
        throw new NullPointerException("authorizationRuleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getProperties() == null) {
        throw new NullPointerException("parameters.Properties");
    }

    // 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("resourceGroupName", resourceGroupName);
        tracingParameters.put("namespaceName", namespaceName);
        tracingParameters.put("notificationHubName", notificationHubName);
        tracingParameters.put("authorizationRuleName", authorizationRuleName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createOrUpdateAuthorizationRuleAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.NotificationHubs";
    url = url + "/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/notificationHubs/";
    url = url + URLEncoder.encode(notificationHubName, "UTF-8");
    url = url + "/AuthorizationRules/";
    url = url + URLEncoder.encode(authorizationRuleName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-09-01");
    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
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode sharedAccessAuthorizationRuleCreateOrUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = sharedAccessAuthorizationRuleCreateOrUpdateParametersValue;

    if (parameters.getLocation() != null) {
        ((ObjectNode) sharedAccessAuthorizationRuleCreateOrUpdateParametersValue).put("location",
                parameters.getLocation());
    }

    if (parameters.getName() != null) {
        ((ObjectNode) sharedAccessAuthorizationRuleCreateOrUpdateParametersValue).put("name",
                parameters.getName());
    }

    ObjectNode propertiesValue = objectMapper.createObjectNode();
    ((ObjectNode) sharedAccessAuthorizationRuleCreateOrUpdateParametersValue).put("properties",
            propertiesValue);

    if (parameters.getProperties().getPrimaryKey() != null) {
        ((ObjectNode) propertiesValue).put("primaryKey", parameters.getProperties().getPrimaryKey());
    }

    if (parameters.getProperties().getSecondaryKey() != null) {
        ((ObjectNode) propertiesValue).put("secondaryKey", parameters.getProperties().getSecondaryKey());
    }

    if (parameters.getProperties().getKeyName() != null) {
        ((ObjectNode) propertiesValue).put("keyName", parameters.getProperties().getKeyName());
    }

    if (parameters.getProperties().getClaimType() != null) {
        ((ObjectNode) propertiesValue).put("claimType", parameters.getProperties().getClaimType());
    }

    if (parameters.getProperties().getClaimValue() != null) {
        ((ObjectNode) propertiesValue).put("claimValue", parameters.getProperties().getClaimValue());
    }

    if (parameters.getProperties().getRights() != null) {
        ArrayNode rightsArray = objectMapper.createArrayNode();
        for (AccessRights rightsItem : parameters.getProperties().getRights()) {
            rightsArray.add(rightsItem.toString());
        }
        ((ObjectNode) propertiesValue).put("rights", rightsArray);
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    ((ObjectNode) propertiesValue).put("createdTime",
            simpleDateFormat.format(parameters.getProperties().getCreatedTime().getTime()));

    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
    ((ObjectNode) propertiesValue).put("modifiedTime",
            simpleDateFormat2.format(parameters.getProperties().getModifiedTime().getTime()));

    ((ObjectNode) propertiesValue).put("revision", parameters.getProperties().getRevision());

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json");

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

        // Create Result
        SharedAccessAuthorizationRuleCreateOrUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new SharedAccessAuthorizationRuleCreateOrUpdateResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                SharedAccessAuthorizationRuleResource valueInstance = new SharedAccessAuthorizationRuleResource();
                result.setValue(valueInstance);

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    valueInstance.setId(idInstance);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    valueInstance.setLocation(locationInstance);
                }

                JsonNode nameValue = responseDoc.get("name");
                if (nameValue != null && nameValue instanceof NullNode == false) {
                    String nameInstance;
                    nameInstance = nameValue.getTextValue();
                    valueInstance.setName(nameInstance);
                }

                JsonNode typeValue = responseDoc.get("type");
                if (typeValue != null && typeValue instanceof NullNode == false) {
                    String typeInstance;
                    typeInstance = typeValue.getTextValue();
                    valueInstance.setType(typeInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                    while (itr.hasNext()) {
                        Map.Entry<String, JsonNode> property = itr.next();
                        String tagsKey = property.getKey();
                        String tagsValue = property.getValue().getTextValue();
                        valueInstance.getTags().put(tagsKey, tagsValue);
                    }
                }

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    SharedAccessAuthorizationRuleProperties propertiesInstance = new SharedAccessAuthorizationRuleProperties();
                    valueInstance.setProperties(propertiesInstance);

                    JsonNode primaryKeyValue = propertiesValue2.get("primaryKey");
                    if (primaryKeyValue != null && primaryKeyValue instanceof NullNode == false) {
                        String primaryKeyInstance;
                        primaryKeyInstance = primaryKeyValue.getTextValue();
                        propertiesInstance.setPrimaryKey(primaryKeyInstance);
                    }

                    JsonNode secondaryKeyValue = propertiesValue2.get("secondaryKey");
                    if (secondaryKeyValue != null && secondaryKeyValue instanceof NullNode == false) {
                        String secondaryKeyInstance;
                        secondaryKeyInstance = secondaryKeyValue.getTextValue();
                        propertiesInstance.setSecondaryKey(secondaryKeyInstance);
                    }

                    JsonNode keyNameValue = propertiesValue2.get("keyName");
                    if (keyNameValue != null && keyNameValue instanceof NullNode == false) {
                        String keyNameInstance;
                        keyNameInstance = keyNameValue.getTextValue();
                        propertiesInstance.setKeyName(keyNameInstance);
                    }

                    JsonNode claimTypeValue = propertiesValue2.get("claimType");
                    if (claimTypeValue != null && claimTypeValue instanceof NullNode == false) {
                        String claimTypeInstance;
                        claimTypeInstance = claimTypeValue.getTextValue();
                        propertiesInstance.setClaimType(claimTypeInstance);
                    }

                    JsonNode claimValueValue = propertiesValue2.get("claimValue");
                    if (claimValueValue != null && claimValueValue instanceof NullNode == false) {
                        String claimValueInstance;
                        claimValueInstance = claimValueValue.getTextValue();
                        propertiesInstance.setClaimValue(claimValueInstance);
                    }

                    JsonNode rightsArray2 = propertiesValue2.get("rights");
                    if (rightsArray2 != null && rightsArray2 instanceof NullNode == false) {
                        for (JsonNode rightsValue : ((ArrayNode) rightsArray2)) {
                            propertiesInstance.getRights()
                                    .add(Enum.valueOf(AccessRights.class, rightsValue.getTextValue()));
                        }
                    }

                    JsonNode createdTimeValue = propertiesValue2.get("createdTime");
                    if (createdTimeValue != null && createdTimeValue instanceof NullNode == false) {
                        Calendar createdTimeInstance;
                        createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeValue.getTextValue());
                        propertiesInstance.setCreatedTime(createdTimeInstance);
                    }

                    JsonNode modifiedTimeValue = propertiesValue2.get("modifiedTime");
                    if (modifiedTimeValue != null && modifiedTimeValue instanceof NullNode == false) {
                        Calendar modifiedTimeInstance;
                        modifiedTimeInstance = DatatypeConverter
                                .parseDateTime(modifiedTimeValue.getTextValue());
                        propertiesInstance.setModifiedTime(modifiedTimeInstance);
                    }

                    JsonNode revisionValue = propertiesValue2.get("revision");
                    if (revisionValue != null && revisionValue instanceof NullNode == false) {
                        int revisionInstance;
                        revisionInstance = revisionValue.getIntValue();
                        propertiesInstance.setRevision(revisionInstance);
                    }
                }
            }

        }
        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.azure.management.notificationhubs.NamespaceOperationsImpl.java

/**
* Returns the description for the specified namespace.  (see
* http://msdn.microsoft.com/library/azure/dn140232.aspx for more
* information)//w w w. j av  a  2  s  .  c o m
*
* @param resourceGroupName Required. The name of the resource group.
* @param namespaceName Required. The namespace name.
* @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 of the Get Namespace operation.
*/
@Override
public NamespaceGetResponse get(String resourceGroupName, String namespaceName)
        throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    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("resourceGroupName", resourceGroupName);
        tracingParameters.put("namespaceName", namespaceName);
        CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.NotificationHubs";
    url = url + "/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-09-01");
    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("Content-Type", "application/json");

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

        // Create Result
        NamespaceGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new NamespaceGetResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                NamespaceResource valueInstance = new NamespaceResource();
                result.setValue(valueInstance);

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    valueInstance.setId(idInstance);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    valueInstance.setLocation(locationInstance);
                }

                JsonNode nameValue = responseDoc.get("name");
                if (nameValue != null && nameValue instanceof NullNode == false) {
                    String nameInstance;
                    nameInstance = nameValue.getTextValue();
                    valueInstance.setName(nameInstance);
                }

                JsonNode typeValue = responseDoc.get("type");
                if (typeValue != null && typeValue instanceof NullNode == false) {
                    String typeInstance;
                    typeInstance = typeValue.getTextValue();
                    valueInstance.setType(typeInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                    while (itr.hasNext()) {
                        Map.Entry<String, JsonNode> property = itr.next();
                        String tagsKey = property.getKey();
                        String tagsValue = property.getValue().getTextValue();
                        valueInstance.getTags().put(tagsKey, tagsValue);
                    }
                }

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    NamespaceProperties propertiesInstance = new NamespaceProperties();
                    valueInstance.setProperties(propertiesInstance);

                    JsonNode nameValue2 = propertiesValue.get("name");
                    if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                        String nameInstance2;
                        nameInstance2 = nameValue2.getTextValue();
                        propertiesInstance.setName(nameInstance2);
                    }

                    JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        propertiesInstance.setProvisioningState(provisioningStateInstance);
                    }

                    JsonNode regionValue = propertiesValue.get("region");
                    if (regionValue != null && regionValue instanceof NullNode == false) {
                        String regionInstance;
                        regionInstance = regionValue.getTextValue();
                        propertiesInstance.setRegion(regionInstance);
                    }

                    JsonNode statusValue = propertiesValue.get("status");
                    if (statusValue != null && statusValue instanceof NullNode == false) {
                        String statusInstance;
                        statusInstance = statusValue.getTextValue();
                        propertiesInstance.setStatus(statusInstance);
                    }

                    JsonNode createdAtValue = propertiesValue.get("createdAt");
                    if (createdAtValue != null && createdAtValue instanceof NullNode == false) {
                        Calendar createdAtInstance;
                        createdAtInstance = DatatypeConverter.parseDateTime(createdAtValue.getTextValue());
                        propertiesInstance.setCreatedAt(createdAtInstance);
                    }

                    JsonNode serviceBusEndpointValue = propertiesValue.get("serviceBusEndpoint");
                    if (serviceBusEndpointValue != null
                            && serviceBusEndpointValue instanceof NullNode == false) {
                        URI serviceBusEndpointInstance;
                        serviceBusEndpointInstance = new URI(serviceBusEndpointValue.getTextValue());
                        propertiesInstance.setServiceBusEndpoint(serviceBusEndpointInstance);
                    }

                    JsonNode subscriptionIdValue = propertiesValue.get("subscriptionId");
                    if (subscriptionIdValue != null && subscriptionIdValue instanceof NullNode == false) {
                        String subscriptionIdInstance;
                        subscriptionIdInstance = subscriptionIdValue.getTextValue();
                        propertiesInstance.setSubscriptionId(subscriptionIdInstance);
                    }

                    JsonNode scaleUnitValue = propertiesValue.get("scaleUnit");
                    if (scaleUnitValue != null && scaleUnitValue instanceof NullNode == false) {
                        String scaleUnitInstance;
                        scaleUnitInstance = scaleUnitValue.getTextValue();
                        propertiesInstance.setScaleUnit(scaleUnitInstance);
                    }

                    JsonNode enabledValue = propertiesValue.get("enabled");
                    if (enabledValue != null && enabledValue instanceof NullNode == false) {
                        boolean enabledInstance;
                        enabledInstance = enabledValue.getBooleanValue();
                        propertiesInstance.setEnabled(enabledInstance);
                    }

                    JsonNode criticalValue = propertiesValue.get("critical");
                    if (criticalValue != null && criticalValue instanceof NullNode == false) {
                        boolean criticalInstance;
                        criticalInstance = criticalValue.getBooleanValue();
                        propertiesInstance.setCritical(criticalInstance);
                    }

                    JsonNode namespaceTypeValue = propertiesValue.get("namespaceType");
                    if (namespaceTypeValue != null && namespaceTypeValue instanceof NullNode == false) {
                        NamespaceType namespaceTypeInstance;
                        namespaceTypeInstance = Enum.valueOf(NamespaceType.class,
                                namespaceTypeValue.getTextValue());
                        propertiesInstance.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:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("unchecked")
private JComponent initializeJComponentForParameter(final String strValue, final ParameterInfo info)
        throws ModelInformationException {
    JComponent field = null;//from w  ww  .  j  av  a 2 s  .  c  om

    if (info.isBoolean()) {
        field = new JCheckBox();
        boolean value = Boolean.parseBoolean(strValue);
        ((JCheckBox) field).setSelected(value);
    } else if (info.isEnum() || info instanceof MasonChooserParameterInfo) {
        Object[] elements = null;
        if (info.isEnum()) {
            final Class<Enum<?>> type = (Class<Enum<?>>) info.getJavaType();
            elements = type.getEnumConstants();
        } else {
            final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) info;
            elements = chooserInfo.getValidStrings();
        }
        final JComboBox list = new JComboBox(elements);

        if (info.isEnum()) {
            try {
                @SuppressWarnings("rawtypes")
                final Object value = Enum.valueOf((Class<? extends Enum>) info.getJavaType(), strValue);
                list.setSelectedItem(value);
            } catch (final IllegalArgumentException e) {
                throw new ModelInformationException(e.getMessage() + " for parameter: " + info.getName() + ".");
            }
        } else {
            try {
                final int value = Integer.parseInt(strValue);
                list.setSelectedIndex(value);
            } catch (final NumberFormatException e) {
                throw new ModelInformationException(
                        "Invalid value for parameter " + info.getName() + " (not a number).");
            }
        }
        field = list;
    } else if (info.isFile()) {
        field = new JPanel();
        final JTextField textField = new JTextField();

        if (!strValue.isEmpty()) {
            final File file = new File(strValue);
            textField.setText(file.getName());
            textField.setToolTipText(file.getAbsolutePath());
        }

        field.add(textField);
    } else if (info instanceof MasonIntervalParameterInfo) {
        field = new JPanel();
        final JTextField textField = new JTextField(strValue);
        field.add(textField);
    } else {
        field = new JTextField(strValue);
    }

    return field;
}