List of usage examples for java.lang Enum valueOf
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
From source file:com.ng.mats.psa.mt.paga.data.JSONObject.java
/** * Get the enum value associated with a key. * // w ww . j av a 2 s . c o m * @param clazz * The type of enum to retrieve. * @param key * A key string. * @param defaultValue * The default in case the value is not found * @return The enum value associated with the key or defaultValue if the * value is not found or cannot be assigned to clazz */ public <E extends Enum<E>> E optEnum(Class<E> clazz, String key, E defaultValue) { try { Object val = this.opt(key); if (NULL.equals(val)) { return defaultValue; } if (clazz.isAssignableFrom(val.getClass())) { // we just checked it! @SuppressWarnings("unchecked") E myE = (E) val; return myE; } return Enum.valueOf(clazz, val.toString()); } catch (IllegalArgumentException | NullPointerException e) { return defaultValue; } }
From source file:com.microsoft.azure.management.websites.WebHostingPlanOperationsImpl.java
/** * Gets details of an existing Web Hosting Plan (see * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/ * for more information)/* w w w . j a v a 2 s . c om*/ * * @param resourceGroupName Required. The name of the resource group. * @param webHostingPlanName Required. The name of the Web Hosting Plan. * @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 Get Web Hosting Plan operation response. */ @Override public WebHostingPlanGetResponse get(String resourceGroupName, String webHostingPlanName) throws IOException, ServiceException, URISyntaxException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (webHostingPlanName == null) { throw new NullPointerException("webHostingPlanName"); } // 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("webHostingPlanName", webHostingPlanName); 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.Web"; url = url + "/serverFarms/"; url = url + URLEncoder.encode(webHostingPlanName, "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 HttpGet httpRequest = new HttpGet(url); // Set Headers // 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 WebHostingPlanGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebHostingPlanGetResponse(); 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) { WebHostingPlan webHostingPlanInstance = new WebHostingPlan(); result.setWebHostingPlan(webHostingPlanInstance); JsonNode propertiesValue = responseDoc.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { WebHostingPlanProperties propertiesInstance = new WebHostingPlanProperties(); webHostingPlanInstance.setProperties(propertiesInstance); JsonNode skuValue = propertiesValue.get("sku"); if (skuValue != null && skuValue instanceof NullNode == false) { SkuOptions skuInstance; skuInstance = Enum.valueOf(SkuOptions.class, skuValue.getTextValue()); propertiesInstance.setSku(skuInstance); } JsonNode numberOfWorkersValue = propertiesValue.get("numberOfWorkers"); if (numberOfWorkersValue != null && numberOfWorkersValue instanceof NullNode == false) { int numberOfWorkersInstance; numberOfWorkersInstance = numberOfWorkersValue.getIntValue(); propertiesInstance.setNumberOfWorkers(numberOfWorkersInstance); } JsonNode workerSizeValue = propertiesValue.get("workerSize"); if (workerSizeValue != null && workerSizeValue instanceof NullNode == false) { WorkerSizeOptions workerSizeInstance; workerSizeInstance = Enum.valueOf(WorkerSizeOptions.class, workerSizeValue.getTextValue()); propertiesInstance.setWorkerSize(workerSizeInstance); } JsonNode adminSiteNameValue = propertiesValue.get("adminSiteName"); if (adminSiteNameValue != null && adminSiteNameValue instanceof NullNode == false) { String adminSiteNameInstance; adminSiteNameInstance = adminSiteNameValue.getTextValue(); propertiesInstance.setAdminSiteName(adminSiteNameInstance); } } JsonNode idValue = responseDoc.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); webHostingPlanInstance.setId(idInstance); } JsonNode nameValue = responseDoc.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); webHostingPlanInstance.setName(nameInstance); } JsonNode locationValue = responseDoc.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); webHostingPlanInstance.setLocation(locationInstance); } 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(); webHostingPlanInstance.getTags().put(tagsKey, tagsValue); } } JsonNode typeValue = responseDoc.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); webHostingPlanInstance.setType(typeInstance); } } } 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.cloud.storage.StorageManagerImpl.java
@Override public PrimaryDataStoreInfo createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceUnavailableException { String providerName = cmd.getStorageProviderName(); DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName); if (storeProvider == null) { storeProvider = _dataStoreProviderMgr.getDefaultPrimaryDataStoreProvider(); if (storeProvider == null) { throw new InvalidParameterValueException("can't find storage provider: " + providerName); }//from w w w . j a v a2s . com } Long clusterId = cmd.getClusterId(); Long podId = cmd.getPodId(); Long zoneId = cmd.getZoneId(); ScopeType scopeType = ScopeType.CLUSTER; String scope = cmd.getScope(); if (scope != null) { try { scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase()); } catch (Exception e) { throw new InvalidParameterValueException("invalid scope for pool " + scope); } } if (scopeType == ScopeType.CLUSTER && clusterId == null) { throw new InvalidParameterValueException("cluster id can't be null, if scope is cluster"); } else if (scopeType == ScopeType.ZONE && zoneId == null) { throw new InvalidParameterValueException("zone id can't be null, if scope is zone"); } HypervisorType hypervisorType = HypervisorType.KVM; if (scopeType == ScopeType.ZONE) { // ignore passed clusterId and podId clusterId = null; podId = null; String hypervisor = cmd.getHypervisor(); if (hypervisor != null) { try { hypervisorType = HypervisorType.getType(hypervisor); } catch (Exception e) { throw new InvalidParameterValueException("invalid hypervisor type " + hypervisor); } } else { throw new InvalidParameterValueException( "Missing parameter hypervisor. Hypervisor type is required to create zone wide primary storage."); } if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.VMware && hypervisorType != HypervisorType.Hyperv && hypervisorType != HypervisorType.LXC && hypervisorType != HypervisorType.Any) { throw new InvalidParameterValueException( "zone wide storage pool is not supported for hypervisor type " + hypervisor); } } Map<String, String> details = extractApiParamAsMap(cmd.getDetails()); DataCenterVO zone = _dcDao.findById(cmd.getZoneId()); if (zone == null) { throw new InvalidParameterValueException("unable to find zone by id " + zoneId); } // Check if zone is disabled Account account = CallContext.current().getCallingAccount(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) { throw new PermissionDeniedException( "Cannot perform this operation, Zone is currently disabled: " + zoneId); } Map<String, Object> params = new HashMap<String, Object>(); params.put("zoneId", zone.getId()); params.put("clusterId", clusterId); params.put("podId", podId); params.put("url", cmd.getUrl()); params.put("tags", cmd.getTags()); params.put("name", cmd.getStoragePoolName()); params.put("details", details); params.put("providerName", storeProvider.getName()); params.put("managed", cmd.isManaged()); params.put("capacityBytes", cmd.getCapacityBytes()); params.put("capacityIops", cmd.getCapacityIops()); DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle(); DataStore store = null; try { store = lifeCycle.initialize(params); if (scopeType == ScopeType.CLUSTER) { ClusterScope clusterScope = new ClusterScope(clusterId, podId, zoneId); lifeCycle.attachCluster(store, clusterScope); } else if (scopeType == ScopeType.ZONE) { ZoneScope zoneScope = new ZoneScope(zoneId); lifeCycle.attachZone(store, zoneScope, hypervisorType); } } catch (Exception e) { s_logger.debug("Failed to add data store: " + e.getMessage(), e); try { // clean up the db, just absorb the exception thrown in deletion with error logged, so that user can get error for adding data store // not deleting data store. if (store != null) { lifeCycle.deleteDataStore(store); } } catch (Exception ex) { s_logger.debug("Failed to clean up storage pool: " + ex.getMessage()); } throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e); } return (PrimaryDataStoreInfo) _dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary); }
From source file:co.cask.cdap.common.conf.Configuration.java
/** * Return value matching this enumerated type. * @param name Property name/*ww w . jav a 2 s .c o m*/ * @throws NullPointerException if the configuration property does not exist * @throws IllegalArgumentException If mapping is illegal for the type * provided */ public <T extends Enum<T>> T getEnum(String name, Class<T> declaringClass) { final String val = get(name); Preconditions.checkNotNull(val); return Enum.valueOf(declaringClass, val); }
From source file:org.jakz.common.JSONObject.java
/** * Get the enum value associated with a key. * //from ww w . j a va 2s . c o m * @param clazz * The type of enum to retrieve. * @param key * A key string. * @param defaultValue * The default in case the value is not found * @return The enum value associated with the key or defaultValue * if the value is not found or cannot be assigned to clazz */ public <E extends Enum<E>> E optEnum(Class<E> clazz, String key, E defaultValue) { try { Object val = this.opt(key); if (NULL.equals(val)) { return defaultValue; } if (clazz.isAssignableFrom(val.getClass())) { // we just checked it! @SuppressWarnings("unchecked") E myE = (E) val; return myE; } return Enum.valueOf(clazz, val.toString()); } catch (IllegalArgumentException e) { return defaultValue; } catch (NullPointerException e) { return defaultValue; } }
From source file:com.microsoft.azure.management.websites.WebSiteOperationsImpl.java
/** * Backups a site on-demand.//from w w w . j a v a2 s . com * * @param resourceGroupName Required. The name of the web space. * @param webSiteName Required. The name of the web site. * @param slotName Optional. The name of the slot. * @param backupRequestEnvelope Required. A backup specification. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The backup record created based on the backup request. */ @Override public WebSiteBackupResponse backup(String resourceGroupName, String webSiteName, String slotName, BackupRequestEnvelope backupRequestEnvelope) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (webSiteName == null) { throw new NullPointerException("webSiteName"); } if (backupRequestEnvelope == null) { throw new NullPointerException("backupRequestEnvelope"); } if (backupRequestEnvelope.getLocation() == null) { throw new NullPointerException("backupRequestEnvelope.Location"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("webSiteName", webSiteName); tracingParameters.put("slotName", slotName); tracingParameters.put("backupRequestEnvelope", backupRequestEnvelope); CloudTracing.enter(invocationId, this, "backupAsync", 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"); } url = url + "/backup"; 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"); httpRequest.setHeader("x-ms-version", "2014-06-01"); // Serialize Request String requestContent = null; JsonNode requestDoc = null; ObjectMapper objectMapper = new ObjectMapper(); ObjectNode backupRequestEnvelopeValue = objectMapper.createObjectNode(); requestDoc = backupRequestEnvelopeValue; if (backupRequestEnvelope.getRequest() != null) { ObjectNode propertiesValue = objectMapper.createObjectNode(); ((ObjectNode) backupRequestEnvelopeValue).put("properties", propertiesValue); if (backupRequestEnvelope.getRequest().getBackupSchedule() != null) { ObjectNode backupScheduleValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("backupSchedule", backupScheduleValue); ((ObjectNode) backupScheduleValue).put("frequencyInterval", backupRequestEnvelope.getRequest().getBackupSchedule().getFrequencyInterval()); if (backupRequestEnvelope.getRequest().getBackupSchedule().getFrequencyUnit() != null) { ((ObjectNode) backupScheduleValue).put("frequencyUnit", backupRequestEnvelope.getRequest().getBackupSchedule().getFrequencyUnit().toString()); } ((ObjectNode) backupScheduleValue).put("keepAtLeastOneBackup", backupRequestEnvelope.getRequest().getBackupSchedule().isKeepAtLeastOneBackup()); if (backupRequestEnvelope.getRequest().getBackupSchedule().getLastExecutionTime() != null) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); ((ObjectNode) backupScheduleValue).put("lastExecutionTime", simpleDateFormat.format(backupRequestEnvelope.getRequest().getBackupSchedule() .getLastExecutionTime().getTime())); } ((ObjectNode) backupScheduleValue).put("retentionPeriodInDays", backupRequestEnvelope.getRequest().getBackupSchedule().getRetentionPeriodInDays()); if (backupRequestEnvelope.getRequest().getBackupSchedule().getStartTime() != null) { SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); ((ObjectNode) backupScheduleValue).put("startTime", simpleDateFormat2.format( backupRequestEnvelope.getRequest().getBackupSchedule().getStartTime().getTime())); } } if (backupRequestEnvelope.getRequest().getDatabases() != null) { if (backupRequestEnvelope.getRequest().getDatabases() instanceof LazyCollection == false || ((LazyCollection) backupRequestEnvelope.getRequest().getDatabases()).isInitialized()) { ArrayNode databasesArray = objectMapper.createArrayNode(); for (DatabaseBackupSetting databasesItem : backupRequestEnvelope.getRequest().getDatabases()) { ObjectNode databaseBackupSettingValue = objectMapper.createObjectNode(); databasesArray.add(databaseBackupSettingValue); if (databasesItem.getConnectionString() != null) { ((ObjectNode) databaseBackupSettingValue).put("connectionString", databasesItem.getConnectionString()); } if (databasesItem.getConnectionStringName() != null) { ((ObjectNode) databaseBackupSettingValue).put("connectionStringName", databasesItem.getConnectionStringName()); } if (databasesItem.getDatabaseType() != null) { ((ObjectNode) databaseBackupSettingValue).put("databaseType", databasesItem.getDatabaseType()); } if (databasesItem.getName() != null) { ((ObjectNode) databaseBackupSettingValue).put("name", databasesItem.getName()); } } ((ObjectNode) propertiesValue).put("databases", databasesArray); } } if (backupRequestEnvelope.getRequest().isEnabled() != null) { ((ObjectNode) propertiesValue).put("enabled", backupRequestEnvelope.getRequest().isEnabled()); } if (backupRequestEnvelope.getRequest().getName() != null) { ((ObjectNode) propertiesValue).put("name", backupRequestEnvelope.getRequest().getName()); } if (backupRequestEnvelope.getRequest().getStorageAccountUrl() != null) { ((ObjectNode) propertiesValue).put("storageAccountUrl", backupRequestEnvelope.getRequest().getStorageAccountUrl()); } } if (backupRequestEnvelope.getId() != null) { ((ObjectNode) backupRequestEnvelopeValue).put("id", backupRequestEnvelope.getId()); } if (backupRequestEnvelope.getName() != null) { ((ObjectNode) backupRequestEnvelopeValue).put("name", backupRequestEnvelope.getName()); } ((ObjectNode) backupRequestEnvelopeValue).put("location", backupRequestEnvelope.getLocation()); if (backupRequestEnvelope.getTags() != null) { ObjectNode tagsDictionary = objectMapper.createObjectNode(); for (Map.Entry<String, String> entry : backupRequestEnvelope.getTags().entrySet()) { String tagsKey = entry.getKey(); String tagsValue = entry.getValue(); ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue); } ((ObjectNode) backupRequestEnvelopeValue).put("tags", tagsDictionary); } if (backupRequestEnvelope.getType() != null) { ((ObjectNode) backupRequestEnvelopeValue).put("type", backupRequestEnvelope.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"); // 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 WebSiteBackupResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebSiteBackupResponse(); 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) { BackupItemEnvelope backupItemInstance = new BackupItemEnvelope(); result.setBackupItem(backupItemInstance); JsonNode propertiesValue2 = responseDoc.get("properties"); if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) { BackupItem propertiesInstance = new BackupItem(); backupItemInstance.setProperties(propertiesInstance); JsonNode storageAccountUrlValue = propertiesValue2.get("storageAccountUrl"); if (storageAccountUrlValue != null && storageAccountUrlValue instanceof NullNode == false) { String storageAccountUrlInstance; storageAccountUrlInstance = storageAccountUrlValue.getTextValue(); propertiesInstance.setStorageAccountUrl(storageAccountUrlInstance); } JsonNode blobNameValue = propertiesValue2.get("blobName"); if (blobNameValue != null && blobNameValue instanceof NullNode == false) { String blobNameInstance; blobNameInstance = blobNameValue.getTextValue(); propertiesInstance.setBlobName(blobNameInstance); } JsonNode nameValue = propertiesValue2.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); propertiesInstance.setName(nameInstance); } JsonNode statusValue = propertiesValue2.get("status"); if (statusValue != null && statusValue instanceof NullNode == false) { BackupItemStatus statusInstance; statusInstance = Enum.valueOf(BackupItemStatus.class, statusValue.getTextValue()); propertiesInstance.setStatus(statusInstance); } JsonNode sizeInBytesValue = propertiesValue2.get("sizeInBytes"); if (sizeInBytesValue != null && sizeInBytesValue instanceof NullNode == false) { long sizeInBytesInstance; sizeInBytesInstance = sizeInBytesValue.getLongValue(); propertiesInstance.setSizeInBytes(sizeInBytesInstance); } JsonNode createdValue = propertiesValue2.get("created"); if (createdValue != null && createdValue instanceof NullNode == false) { Calendar createdInstance; createdInstance = DatatypeConverter.parseDateTime(createdValue.getTextValue()); propertiesInstance.setCreated(createdInstance); } JsonNode logValue = propertiesValue2.get("log"); if (logValue != null && logValue instanceof NullNode == false) { String logInstance; logInstance = logValue.getTextValue(); propertiesInstance.setLog(logInstance); } JsonNode databasesArray2 = propertiesValue2.get("databases"); if (databasesArray2 != null && databasesArray2 instanceof NullNode == false) { for (JsonNode databasesValue : ((ArrayNode) databasesArray2)) { DatabaseBackupSetting databaseBackupSettingInstance = new DatabaseBackupSetting(); propertiesInstance.getDatabases().add(databaseBackupSettingInstance); JsonNode connectionStringValue = databasesValue.get("connectionString"); if (connectionStringValue != null && connectionStringValue instanceof NullNode == false) { String connectionStringInstance; connectionStringInstance = connectionStringValue.getTextValue(); databaseBackupSettingInstance.setConnectionString(connectionStringInstance); } JsonNode connectionStringNameValue = databasesValue.get("connectionStringName"); if (connectionStringNameValue != null && connectionStringNameValue instanceof NullNode == false) { String connectionStringNameInstance; connectionStringNameInstance = connectionStringNameValue.getTextValue(); databaseBackupSettingInstance .setConnectionStringName(connectionStringNameInstance); } JsonNode databaseTypeValue = databasesValue.get("databaseType"); if (databaseTypeValue != null && databaseTypeValue instanceof NullNode == false) { String databaseTypeInstance; databaseTypeInstance = databaseTypeValue.getTextValue(); databaseBackupSettingInstance.setDatabaseType(databaseTypeInstance); } JsonNode nameValue2 = databasesValue.get("name"); if (nameValue2 != null && nameValue2 instanceof NullNode == false) { String nameInstance2; nameInstance2 = nameValue2.getTextValue(); databaseBackupSettingInstance.setName(nameInstance2); } } } JsonNode scheduledValue = propertiesValue2.get("scheduled"); if (scheduledValue != null && scheduledValue instanceof NullNode == false) { boolean scheduledInstance; scheduledInstance = scheduledValue.getBooleanValue(); propertiesInstance.setScheduled(scheduledInstance); } JsonNode lastRestoreTimeStampValue = propertiesValue2.get("lastRestoreTimeStamp"); if (lastRestoreTimeStampValue != null && lastRestoreTimeStampValue instanceof NullNode == false) { Calendar lastRestoreTimeStampInstance; lastRestoreTimeStampInstance = DatatypeConverter .parseDateTime(lastRestoreTimeStampValue.getTextValue()); propertiesInstance.setLastRestoreTimeStamp(lastRestoreTimeStampInstance); } JsonNode finishedTimeStampValue = propertiesValue2.get("finishedTimeStamp"); if (finishedTimeStampValue != null && finishedTimeStampValue instanceof NullNode == false) { Calendar finishedTimeStampInstance; finishedTimeStampInstance = DatatypeConverter .parseDateTime(finishedTimeStampValue.getTextValue()); propertiesInstance.setFinishedTimeStamp(finishedTimeStampInstance); } JsonNode correlationIdValue = propertiesValue2.get("correlationId"); if (correlationIdValue != null && correlationIdValue instanceof NullNode == false) { String correlationIdInstance; correlationIdInstance = correlationIdValue.getTextValue(); propertiesInstance.setCorrelationId(correlationIdInstance); } } JsonNode idValue = responseDoc.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); backupItemInstance.setId(idInstance); } JsonNode nameValue3 = responseDoc.get("name"); if (nameValue3 != null && nameValue3 instanceof NullNode == false) { String nameInstance3; nameInstance3 = nameValue3.getTextValue(); backupItemInstance.setName(nameInstance3); } JsonNode locationValue = responseDoc.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); backupItemInstance.setLocation(locationInstance); } 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 tagsKey2 = property.getKey(); String tagsValue2 = property.getValue().getTextValue(); backupItemInstance.getTags().put(tagsKey2, tagsValue2); } } JsonNode typeValue = responseDoc.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); backupItemInstance.setType(typeInstance); } } } 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:io.stallion.dataAccess.filtering.FilterChain.java
/** * Hydrate the FilterOperation.typedValue based on gueessing or reflecting * on the type of the property as passed in. * * @param op// w w w.j av a 2 s. c om * @param propValue */ private void hydrateTypedValue(FilterOperation op, Object propValue) { if (op.getTypedValue() != null) { return; } if (op.getOriginalValue() == null) { return; } if (op.getOriginalValue().getClass().equals(propValue.getClass())) { op.setTypedValue(op.getOriginalValue()); return; } if (op.getOriginalValue().getClass().equals(String.class)) { String val = (String) op.getOriginalValue(); if (propValue != null) { if (propValue instanceof Enum) { op.setTypedValue(Enum.valueOf((Class<? extends Enum>) propValue.getClass(), val)); } else if (propValue instanceof ZonedDateTime) { if (((String) op.getOriginalValue()).length() == 16) { op.setTypedValue(ZonedDateTime.parse((String) op.getOriginalValue() + ":00 UTC", DateUtils.SQL_FORMAT_ZONED)); } else if (((String) op.getOriginalValue()).length() == 19) { op.setTypedValue(ZonedDateTime.parse((String) op.getOriginalValue() + " UTC", DateUtils.SQL_FORMAT_ZONED)); } else { op.setTypedValue(ZonedDateTime.parse((String) op.getOriginalValue(), DateUtils.ISO_FORMAT)); } } else if (propValue.getClass().equals(Integer.class)) { op.setTypedValue(Integer.parseInt(val)); } else if (propValue.getClass().equals(Long.class)) { op.setTypedValue(Long.parseLong(val)); } else if (propValue.getClass().equals(Boolean.class)) { op.setTypedValue(Boolean.parseBoolean(val)); } else { op.setTypedValue(op.getOriginalValue()); } } else { op.setTypedValue(op.getOriginalValue()); } } else if (op.getOriginalValue() instanceof BigInteger) { op.setTypedValue(((BigInteger) op.getOriginalValue()).longValue()); } else if (op.getOriginalValue() instanceof Integer && propValue instanceof Long) { op.setTypedValue(new Long((Integer) op.getOriginalValue())); } else if (op.getOriginalValue() instanceof Integer && propValue instanceof Float) { op.setTypedValue(((Integer) op.getOriginalValue()).floatValue()); } else if (op.getOriginalValue() instanceof Integer && propValue instanceof Double) { op.setTypedValue(((Integer) op.getOriginalValue()).doubleValue()); } else if (op.getOriginalValue() instanceof Long && propValue instanceof Double) { op.setTypedValue(((Long) op.getOriginalValue()).doubleValue()); } else if (op.getOriginalValue() instanceof Long && propValue instanceof Float) { op.setTypedValue(((Long) op.getOriginalValue()).floatValue()); } else if (propValue instanceof Boolean) { if (op.getOriginalValue() instanceof Integer || op.getOriginalValue() instanceof Long) { if ((Integer) op.getOriginalValue() == 0) { op.setTypedValue(false); } else if ((Integer) op.getOriginalValue() == 1) { op.setTypedValue(true); } } } if (op.getTypedValue() == null) { op.setTypedValue(op.getOriginalValue()); } }
From source file:co.cask.cdap.common.conf.Configuration.java
/** * Return value matching this enumerated type. * @param name Property name/*from w w w. j av a2 s .co m*/ * @param defaultValue Value returned if no mapping exists * @throws IllegalArgumentException If mapping is illegal for the type * provided */ public <T extends Enum<T>> T getEnum(String name, T defaultValue) { final String val = get(name); return null == val ? defaultValue : Enum.valueOf(defaultValue.getDeclaringClass(), val); }
From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java
/** * Sets the default value on the attribute model (translates a String to the appropriate type) * /*from w w w. jav a 2 s . c o m*/ * @param model * @param defaultValue */ @SuppressWarnings("unchecked") private void setDefaultValue(AttributeModelImpl model, String defaultValue) { if (model.getType().isEnum()) { model.setDefaultValue(Enum.valueOf(model.getType().asSubclass(Enum.class), defaultValue)); } else if (model.getType().equals(Date.class)) { SimpleDateFormat fmt = new SimpleDateFormat(model.getDisplayFormat()); try { model.setDefaultValue(fmt.parseObject(defaultValue)); } catch (ParseException e) { throw new OCSRuntimeException("Cannot parse default date value: " + defaultValue + " with format: " + model.getDisplayFormat()); } } else { model.setDefaultValue(ClassUtils.instantiateClass(model.getType(), defaultValue)); } }
From source file:com.alliander.osgp.acceptancetests.adhocmanagement.GetStatusSteps.java
@DomainStep("the get get status response request should return a get status response with result (.*), description (.*), (.*), (.*), (.*), (.*), (.*), (.*), and (.*)") public boolean thenTheGetGetStatusResponseRequestShouldReturnAGetStatusResponse(final String result, final String description, final String preferredLinktype, final String actualLinktype, final String lighttype, final String eventnotifications, final String index, final String on, final String dimValue) { LOGGER.info(/*from w w w . jav a 2s. c o m*/ "THEN: the get get status response request should return a get status response with result: {}, description: {}, preferredLinktype: {}, actualLinktype: {}, lighttype: {}, eventnotification: {}, index: {}, on: {}, dimValue: {}", result, description, preferredLinktype, actualLinktype, lighttype, eventnotifications, index, on, dimValue); try { if ("NOT_OK".equals(result)) { Assert.assertNull("Set Schedule Response should be null", this.response); Assert.assertNotNull("Throwable should not be null", this.throwable); Assert.assertTrue("Throwable should contain a validation exception", this.throwable.getCause() instanceof ValidationException); } else { // Check if the GetStatusResponse is not null. Assert.assertNotNull("GetStatusResponse response is null", this.response); // Check the result. String expected = result.equals(NULL) ? null : result; String actual = this.response.getResult().toString(); Assert.assertTrue("Invalid result, found: " + actual + " , expected: " + expected, actual.equals(expected)); if (this.response.getResult().equals("OK")) { // Check if the DeviceStatus is not null. Assert.assertNotNull("DeviceStatus is null", this.response.getDeviceStatus()); try { // Check the preferredLinktype. expected = preferredLinktype.equals(NULL) ? null : preferredLinktype; actual = this.response.getDeviceStatus().getPreferredLinkType() == null ? null : this.response.getDeviceStatus().getPreferredLinkType().toString(); Assert.assertTrue( "Invalid preferredLinktype, found: " + actual + " , expected: " + expected, actual.equals(expected)); } catch (final Exception e) { } try { // Check the actualLinktype. expected = actualLinktype.equals(NULL) ? null : actualLinktype; actual = this.response.getDeviceStatus().getActualLinkType() == null ? null : this.response.getDeviceStatus().getActualLinkType().toString(); Assert.assertTrue("Invalid actualLinktype, found: " + actual + " , expected: " + expected, actual.equals(expected)); } catch (final Exception e) { } try { // Check the lighttype. expected = lighttype.equals(NULL) ? null : lighttype; actual = this.response.getDeviceStatus().getLightType() == null ? null : this.response.getDeviceStatus().getLightType().toString(); Assert.assertTrue("Invalid lighttype, found: " + actual + " , expected: " + expected, actual.equals(expected)); } catch (final Exception e) { } // Check the eventnotifications. final HashSet<com.alliander.osgp.adapter.ws.schema.publiclighting.adhocmanagement.EventNotificationType> expectedEventNotificationTypes = new HashSet<>(); if (StringUtils.isNotBlank(eventnotifications)) { for (final String event : eventnotifications.split(",")) { expectedEventNotificationTypes.add(Enum.valueOf( com.alliander.osgp.adapter.ws.schema.publiclighting.adhocmanagement.EventNotificationType.class, event)); } } final HashSet<com.alliander.osgp.adapter.ws.schema.publiclighting.adhocmanagement.EventNotificationType> actualEventNotificationTypes = new HashSet<>( this.response.getDeviceStatus().getEventNotifications()); Assert.assertEquals("Event notifications should equal expected value", expectedEventNotificationTypes, actualEventNotificationTypes); final List<LightValue> lightValues = this.response.getDeviceStatus().getLightValues(); // Check if lightValues not is null. Assert.assertNotNull("LightValues is null", lightValues); for (final LightValue lightValue : lightValues) { // Check the on boolean. expected = on.equals(NULL) ? null : on; actual = lightValue.isOn() + ""; Assert.assertTrue("Invalid lightValue.isOn, found: " + actual + " , expected: " + expected, actual.equals(expected)); // Check the dimValue. expected = dimValue.equals(NULL) ? null : dimValue; actual = lightValue.getDimValue().toString(); Assert.assertTrue( "Invalid lightValue.dimValue, found: " + actual + " , expected: " + expected, actual.equals(expected)); // Check the index. expected = index.equals(NULL) ? null : index; actual = lightValue.getIndex().toString(); Assert.assertTrue("Invalid lightValue.index, found: " + actual + " , expected: " + expected, actual.equals(expected)); } } } } catch (final Throwable t) { LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage()); return false; } return true; }