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.openshift.internal.restclient.DefaultClient.java
private <T extends Enum<T>> List<T> getVersion(Class<T> klass, String endpoint) { try {//from w w w.j a v a 2 s . c o m final URL url = new URL(this.baseUrl, endpoint); LOGGER.debug(url.toString()); String response = client.get(url, IHttpClient.DEFAULT_READ_TIMEOUT); LOGGER.debug(response); ModelNode json = ModelNode.fromJSONString(response); List<ModelNode> versionNodes = json.get("versions").asList(); List<T> versions = new ArrayList<T>(versionNodes.size()); for (ModelNode node : versionNodes) { try { versions.add(Enum.valueOf(klass, node.asString())); } catch (IllegalArgumentException e) { LOGGER.warn(String.format("Unsupported server version '%s' for '%s'", node.asString(), klass.getSimpleName())); } } return versions; } catch (MalformedURLException e) { LOGGER.error("Exception", e); throw new OpenShiftException(e, ""); } catch (SocketTimeoutException e) { LOGGER.error("Exception", e); throw new OpenShiftException(e, ""); //HACK - This gets us around a server issue } catch (HttpClientException e) { if (e instanceof NotFoundException) { throw new com.openshift.restclient.NotFoundException(e); } if (e.getResponseCode() != 403) { throw e; } LOGGER.error("Unauthorized exception. Can system:anonymous get the API endpoint", e); return new ArrayList<T>(); } }
From source file:org.projectforge.business.user.UserPrefDao.java
/** * @param value//from w ww .ja v a2s . c om * @return * @see #convertParameterValueToString(Object) */ @SuppressWarnings("unchecked") public Object getParameterValue(final Class<?> type, final String str) { if (str == null) { return null; } if (type.isAssignableFrom(String.class) == true) { return str; } else if (type.isAssignableFrom(Integer.class) == true) { return Integer.valueOf(str); } else if (DefaultBaseDO.class.isAssignableFrom(type) == true) { final Integer id = NumberHelper.parseInteger(str); if (id != null) { if (PFUserDO.class.isAssignableFrom(type) == true) { return userDao.getOrLoad(id); } else if (TaskDO.class.isAssignableFrom(type) == true) { return taskDao.getOrLoad(id); } else if (Kost2DO.class.isAssignableFrom(type) == true) { return kost2Dao.getOrLoad(id); } else if (ProjektDO.class.isAssignableFrom(type) == true) { return projektDao.getOrLoad(id); } else { log.warn("getParameterValue: Type '" + type + "' not supported. May-be it does not work."); return getHibernateTemplate().load(type, id); } } else { return null; } } else if (KundeDO.class.isAssignableFrom(type) == true) { final Integer id = NumberHelper.parseInteger(str); if (id != null) { return kundeDao.getOrLoad(id); } else { return null; } } else if (type.isEnum() == true) { return Enum.valueOf((Class<Enum>) type, str); } log.error("UserPrefDao does not yet support parameters from type: " + type); return null; }
From source file:org.chililog.server.workbench.workers.RepositoryRuntimeWorker.java
/** * Load our criteria from query string and headers (in case it is too big for query string) * //from w ww . j a v a 2s . co m * @returns query criteria * @throws ChiliLogException * @throws ParseException */ private RepositoryEntryListCriteria loadCriteria() throws ChiliLogException, ParseException { String s; RepositoryEntryListCriteria criteria = new RepositoryEntryListCriteria(); this.loadBaseListCriteriaParameters(criteria); s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_FIELDS_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_FIELDS_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setFields(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_FROM_TIMESTAMP_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_FROM_TIMESTAMP_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setFrom(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_TO_TIMESTAMP_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_TO_TIMESTAMP_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setTo(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_KEYWORD_USAGE_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_KEYWORD_USAGE_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setKeywordUsage(Enum.valueOf(RepositoryEntryListCriteria.KeywordUsage.class, s)); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_CONDITIONS_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_CONDITIONS_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setConditions(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_KEYWORD_USAGE_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_KEYWORD_USAGE_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setKeywordUsage(Enum.valueOf(RepositoryEntryListCriteria.KeywordUsage.class, s)); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_KEYWORDS_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_KEYWORDS_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setKeywords(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_SEVERITY_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_SEVERITY_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setSeverity(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_HOST_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_HOST_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setHost(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_SOURCE_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_SOURCE_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setSource(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_CONDITIONS_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_CONDITIONS_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setConditions(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_ORDER_BY_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_ORDER_BY_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setOrderBy(s.trim()); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_INITIAL_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_INITIAL_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setInitial(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_INITIAL_HEADER_NAME, ENTRY_QUERY_REDUCE_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setReduceFunction(s); } s = this.getQueryStringOrHeaderValue(ENTRY_QUERY_FINALIZE_QUERYSTRING_PARAMETER_NAME, ENTRY_QUERY_FINALIZE_HEADER_NAME, true); if (!StringUtils.isBlank(s)) { criteria.setFinalizeFunction(s); } return criteria; }
From source file:com.microsoft.azure.management.compute.ComputeManagementClientImpl.java
/** * The Get Delete Operation Status operation returns the status of the * specified operation. After calling an asynchronous operation, you can * call GetDeleteOperationStatus to determine whether the operation has * succeeded, failed, or is still in progress. * * @param operationStatusLink Required. Location value returned by the Begin * operation./*from w ww . ja v a 2 s. c o m*/ * @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 compute long running operation response. */ @Override public DeleteOperationResponse getDeleteOperationStatus(String operationStatusLink) throws IOException, ServiceException { // Validate if (operationStatusLink == null) { throw new NullPointerException("operationStatusLink"); } // 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("operationStatusLink", operationStatusLink); CloudTracing.enter(invocationId, this, "getDeleteOperationStatusAsync", tracingParameters); } // Construct URL String url = ""; url = url + operationStatusLink; 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.getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DeleteOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DeleteOperationResponse(); 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) { JsonNode operationIdValue = responseDoc.get("operationId"); if (operationIdValue != null && operationIdValue instanceof NullNode == false) { String operationIdInstance; operationIdInstance = operationIdValue.getTextValue(); result.setTrackingOperationId(operationIdInstance); } JsonNode statusValue = responseDoc.get("status"); if (statusValue != null && statusValue instanceof NullNode == false) { OperationStatus statusInstance; statusInstance = Enum.valueOf(OperationStatus.class, statusValue.getTextValue()); result.setStatus(statusInstance); } JsonNode startTimeValue = responseDoc.get("startTime"); if (startTimeValue != null && startTimeValue instanceof NullNode == false) { Calendar startTimeInstance; startTimeInstance = DatatypeConverter.parseDateTime(startTimeValue.getTextValue()); result.setStartTime(startTimeInstance); } JsonNode endTimeValue = responseDoc.get("endTime"); if (endTimeValue != null && endTimeValue instanceof NullNode == false) { Calendar endTimeInstance; endTimeInstance = DatatypeConverter.parseDateTime(endTimeValue.getTextValue()); result.setEndTime(endTimeInstance); } JsonNode errorValue = responseDoc.get("error"); if (errorValue != null && errorValue instanceof NullNode == false) { ApiError errorInstance = new ApiError(); result.setError(errorInstance); JsonNode detailsArray = errorValue.get("details"); if (detailsArray != null && detailsArray instanceof NullNode == false) { for (JsonNode detailsValue : ((ArrayNode) detailsArray)) { ApiErrorBase apiErrorBaseInstance = new ApiErrorBase(); errorInstance.getDetails().add(apiErrorBaseInstance); JsonNode codeValue = detailsValue.get("code"); if (codeValue != null && codeValue instanceof NullNode == false) { String codeInstance; codeInstance = codeValue.getTextValue(); apiErrorBaseInstance.setCode(codeInstance); } JsonNode targetValue = detailsValue.get("target"); if (targetValue != null && targetValue instanceof NullNode == false) { String targetInstance; targetInstance = targetValue.getTextValue(); apiErrorBaseInstance.setTarget(targetInstance); } JsonNode messageValue = detailsValue.get("message"); if (messageValue != null && messageValue instanceof NullNode == false) { String messageInstance; messageInstance = messageValue.getTextValue(); apiErrorBaseInstance.setMessage(messageInstance); } } } JsonNode innererrorValue = errorValue.get("innererror"); if (innererrorValue != null && innererrorValue instanceof NullNode == false) { InnerError innererrorInstance = new InnerError(); errorInstance.setInnerError(innererrorInstance); JsonNode exceptiontypeValue = innererrorValue.get("exceptiontype"); if (exceptiontypeValue != null && exceptiontypeValue instanceof NullNode == false) { String exceptiontypeInstance; exceptiontypeInstance = exceptiontypeValue.getTextValue(); innererrorInstance.setExceptionType(exceptiontypeInstance); } JsonNode errordetailValue = innererrorValue.get("errordetail"); if (errordetailValue != null && errordetailValue instanceof NullNode == false) { String errordetailInstance; errordetailInstance = errordetailValue.getTextValue(); innererrorInstance.setErrorDetail(errordetailInstance); } } JsonNode codeValue2 = errorValue.get("code"); if (codeValue2 != null && codeValue2 instanceof NullNode == false) { String codeInstance2; codeInstance2 = codeValue2.getTextValue(); errorInstance.setCode(codeInstance2); } JsonNode targetValue2 = errorValue.get("target"); if (targetValue2 != null && targetValue2 instanceof NullNode == false) { String targetInstance2; targetInstance2 = targetValue2.getTextValue(); errorInstance.setTarget(targetInstance2); } JsonNode messageValue2 = errorValue.get("message"); if (messageValue2 != null && messageValue2 instanceof NullNode == false) { String messageInstance2; messageInstance2 = messageValue2.getTextValue(); errorInstance.setMessage(messageInstance2); } } } } 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:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputSaslHelper.java
private static CipherOptionHelper createCipherHelper27(Class<?> cipherOptionClass) throws ClassNotFoundException, NoSuchMethodException { @SuppressWarnings("rawtypes") Class<? extends Enum> cipherSuiteClass = Class.forName("org.apache.hadoop.crypto.CipherSuite") .asSubclass(Enum.class); @SuppressWarnings("unchecked") final Enum<?> aesCipherSuite = Enum.valueOf(cipherSuiteClass, "AES_CTR_NOPADDING"); final Constructor<?> cipherOptionConstructor = cipherOptionClass.getConstructor(cipherSuiteClass); final Constructor<?> cipherOptionWithKeyAndIvConstructor = cipherOptionClass .getConstructor(cipherSuiteClass, byte[].class, byte[].class, byte[].class, byte[].class); final Method getCipherSuiteMethod = cipherOptionClass.getMethod("getCipherSuite"); final Method getInKeyMethod = cipherOptionClass.getMethod("getInKey"); final Method getInIvMethod = cipherOptionClass.getMethod("getInIv"); final Method getOutKeyMethod = cipherOptionClass.getMethod("getOutKey"); final Method getOutIvMethod = cipherOptionClass.getMethod("getOutIv"); Class<?> pbHelperClass; try {/*from www . j a va 2 s . c o m*/ pbHelperClass = Class.forName("org.apache.hadoop.hdfs.protocolPB.PBHelperClient"); } catch (ClassNotFoundException e) { LOG.debug("No PBHelperClient class found, should be hadoop 2.7-", e); pbHelperClass = org.apache.hadoop.hdfs.protocolPB.PBHelper.class; } final Method convertCipherOptionsMethod = pbHelperClass.getMethod("convertCipherOptions", List.class); final Method convertCipherOptionProtosMethod = pbHelperClass.getMethod("convertCipherOptionProtos", List.class); final Method addAllCipherOptionMethod = DataTransferEncryptorMessageProto.Builder.class .getMethod("addAllCipherOption", Iterable.class); final Method getCipherOptionListMethod = DataTransferEncryptorMessageProto.class .getMethod("getCipherOptionList"); return new CipherOptionHelper() { @Override public byte[] getOutKey(Object cipherOption) { try { return (byte[]) getOutKeyMethod.invoke(cipherOption); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public byte[] getOutIv(Object cipherOption) { try { return (byte[]) getOutIvMethod.invoke(cipherOption); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public byte[] getInKey(Object cipherOption) { try { return (byte[]) getInKeyMethod.invoke(cipherOption); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public byte[] getInIv(Object cipherOption) { try { return (byte[]) getInIvMethod.invoke(cipherOption); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public Object getCipherSuite(Object cipherOption) { try { return getCipherSuiteMethod.invoke(cipherOption); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public List<Object> getCipherOptions(Configuration conf) throws IOException { // Negotiate cipher suites if configured. Currently, the only supported // cipher suite is AES/CTR/NoPadding, but the protocol allows multiple // values for future expansion. String cipherSuites = conf.get(DFS_ENCRYPT_DATA_TRANSFER_CIPHER_SUITES_KEY); if (cipherSuites == null || cipherSuites.isEmpty()) { return null; } if (!cipherSuites.equals(AES_CTR_NOPADDING)) { throw new IOException(String.format("Invalid cipher suite, %s=%s", DFS_ENCRYPT_DATA_TRANSFER_CIPHER_SUITES_KEY, cipherSuites)); } Object option; try { option = cipherOptionConstructor.newInstance(aesCipherSuite); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } List<Object> cipherOptions = Lists.newArrayListWithCapacity(1); cipherOptions.add(option); return cipherOptions; } private Object unwrap(Object option, SaslClient saslClient) throws IOException { byte[] inKey = getInKey(option); if (inKey != null) { inKey = saslClient.unwrap(inKey, 0, inKey.length); } byte[] outKey = getOutKey(option); if (outKey != null) { outKey = saslClient.unwrap(outKey, 0, outKey.length); } try { return cipherOptionWithKeyAndIvConstructor.newInstance(getCipherSuite(option), inKey, getInIv(option), outKey, getOutIv(option)); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public Object getCipherOption(DataTransferEncryptorMessageProto proto, boolean isNegotiatedQopPrivacy, SaslClient saslClient) throws IOException { List<Object> cipherOptions; try { cipherOptions = (List<Object>) convertCipherOptionProtosMethod.invoke(null, getCipherOptionListMethod.invoke(proto)); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } if (cipherOptions == null || cipherOptions.isEmpty()) { return null; } Object cipherOption = cipherOptions.get(0); return isNegotiatedQopPrivacy ? unwrap(cipherOption, saslClient) : cipherOption; } @Override public void addCipherOptions(Builder builder, List<Object> cipherOptions) { try { addAllCipherOptionMethod.invoke(builder, convertCipherOptionsMethod.invoke(null, cipherOptions)); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } }; }
From source file:com.cloudera.sqoop.SqoopOptions.java
@SuppressWarnings("unchecked") /**/*from w w w . j a va2s . c om*/ * Given a set of properties, load this into the current SqoopOptions * instance. */ public void loadProperties(Properties props) { try { Field[] fields = getClass().getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { f.setInt(this, getIntProperty(props, propName, f.getInt(this))); } else if (typ.equals(boolean.class)) { f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this))); } else if (typ.equals(long.class)) { f.setLong(this, getLongProperty(props, propName, f.getLong(this))); } else if (typ.equals(String.class)) { f.set(this, props.getProperty(propName, (String) f.get(this))); } else if (typ.equals(Integer.class)) { String value = props.getProperty(propName, f.get(this) == null ? "null" : f.get(this).toString()); f.set(this, value.equals("null") ? null : new Integer(value)); } else if (typ.isEnum()) { f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString()))); } else { throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } // Now load properties that were stored with special types, or require // additional logic to set. if (getBooleanProperty(props, "db.require.password", false)) { // The user's password was stripped out from the metastore. // Require that the user enter it now. setPasswordFromConsole(); } else { this.password = props.getProperty("db.password", this.password); } if (this.jarDirIsAuto) { // We memoized a user-specific nonce dir for compilation to the data // store. Disregard that setting and create a new nonce dir. String localUsername = System.getProperty("user.name", "unknown"); this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile"); } String colListStr = props.getProperty("db.column.list", null); if (null != colListStr) { this.columns = listToArray(colListStr); } this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs); // Delimiters were previously memoized; don't let the tool override // them with defaults. this.areDelimsManuallySet = true; }
From source file:com.thinkbiganalytics.policy.BasePolicyAnnotationTransformer.java
public Object convertStringToObject(String value, Class type) { if (type.isEnum()) { return Enum.valueOf(type, value); } else if (String.class.equals(type)) { return value; }// ww w .ja va 2 s . c o m if (StringUtils.isBlank(value)) { return null; } else if (Number.class.equals(type)) { return NumberUtils.createNumber(value); } else if (Integer.class.equals(type) || Integer.TYPE.equals(type)) { return new Integer(value); } else if (Long.class.equals(type) || Long.TYPE.equals(type)) { return Long.valueOf(value); } else if (Double.class.equals(type) || Double.TYPE.equals(type)) { return Double.valueOf(value); } else if (Float.class.equals(type) || Float.TYPE.equals(type)) { return Float.valueOf(value); } else if (Pattern.class.equals(type)) { return Pattern.compile(value); } else if (Boolean.class.equals(type) || Boolean.TYPE.equals(type)) { return BooleanUtils.toBoolean(value); } else { throw new IllegalArgumentException( "Unable to convert the value " + value + " to an object of type " + type.getName()); } }
From source file:com.alliander.osgp.acceptancetests.adhocmanagement.GetStatusSteps.java
@DomainStep("a get status response message for domainType (.*) with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)") public void givenAGetStatusResponseMessageIsFoundInQueue(final String domainType, final String correlationId, final String deviceId, final String qresult, final String qdescription, final String preferredLinkType, final String actualLinkType, final String lightType, final String eventNotifications, final String index, final String on, final String dimValue, final Boolean isFound) { LOGGER.info(//w w w. j a v a 2 s. c om "GIVEN: \"a get status response message for domainType {} with correlationId {}, deviceId {}, qresult {} and qdescription {} is found {}\".", domainType, correlationId, deviceId, qresult, qdescription, isFound); if (isFound) { final ObjectMessage messageMock = mock(ObjectMessage.class); try { when(messageMock.getJMSCorrelationID()).thenReturn(correlationId); when(messageMock.getStringProperty("OrganisationIdentification")).thenReturn(ORGANISATION_ID); when(messageMock.getStringProperty("DeviceIdentification")).thenReturn(deviceId); final LinkType prefLinkType = StringUtils.isBlank(preferredLinkType) ? null : Enum.valueOf(LinkType.class, preferredLinkType); final LinkType actLinkType = StringUtils.isBlank(actualLinkType) ? null : Enum.valueOf(LinkType.class, actualLinkType); final LightType lt = StringUtils.isBlank(lightType) ? null : Enum.valueOf(LightType.class, lightType); // EventNotificationTypes int mask = 0; if (StringUtils.isNotBlank(eventNotifications)) { for (final String event : eventNotifications.split(",")) { mask += (Enum.valueOf(EventNotificationType.class, event)).getValue(); } } final ResponseMessage message; final ResponseMessageResultType result = ResponseMessageResultType.valueOf(qresult); Serializable dataObject = null; if (result.equals(ResponseMessageResultType.NOT_OK)) { dataObject = new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.UNKNOWN, new ValidationException()); message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId, result, (OsgpException) dataObject, dataObject); } else { if (domainType.equals(DomainType.PUBLIC_LIGHTING.name())) { // DomainType.PUBLIC_LIGHTING dataObject = new DeviceStatus(null, prefLinkType, actLinkType, lt, mask); } else { // DomainType.TARIFF_SWITCHING dataObject = new DeviceStatusMapped(null, null, prefLinkType, actLinkType, lt, mask); } message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId, result, null, dataObject); } when(messageMock.getObject()).thenReturn(message); } catch (final JMSException e) { e.printStackTrace(); } when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))) .thenReturn(messageMock); } else { when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))).thenReturn(null); } }
From source file:com.linecorp.armeria.common.thrift.text.TTextProtocol.java
@Override public int readI32() throws TException { Class<?> fieldClass = getCurrentFieldClassIfIs(TEnum.class); if (fieldClass != null) { // Enum fields may be set by string, even though they represent integers. getCurrentContext().read();/*from w w w.j a v a 2 s . c om*/ JsonNode elem = getCurrentContext().getCurrentChild(); if (elem.isInt()) { return TypedParser.INTEGER.readFromJsonElement(elem); } else if (elem.isTextual()) { @SuppressWarnings("rawtypes,unchecked") // All TEnum are enums Class casted = (Class) fieldClass; TEnum tEnum = (TEnum) Enum.valueOf(casted, TypedParser.STRING.readFromJsonElement(elem)); return tEnum.getValue(); } else { throw new TTransportException( "invalid value type for enum field: " + elem.getNodeType() + " (" + elem + ')'); } } else { return readNameOrValue(TypedParser.INTEGER); } }
From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.excelimport.EntityDataImporter.java
/** * @param typeName//from w w w . j a v a2 s .c o m * @param cellValue * @return the enum value for the given typeName and the enum value given as String in the cell value; * or null if the value is not found. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private Object resolveJavaEnum(String typeName, Object cellValue) { Object result = null; try { Class<?> clazz = Class.forName(typeName); if (clazz.isEnum()) { return Enum.valueOf(((Class<Enum>) clazz), cellValue.toString()); } else { logError("Type {0} is not an enum. Can not find value for {1}", typeName, cellValue.toString()); } } catch (ClassNotFoundException e) { logError("Error setting {0} to {1}: {2} {3}", typeName, cellValue.toString(), e.getClass().getName(), e.getMessage()); } catch (SecurityException e) { logError("Error setting {0} to {1}: {2} {3}", typeName, cellValue.toString(), e.getClass().getName(), e.getMessage()); } catch (IllegalArgumentException e) { logError("Error setting {0} to {1}: {2} {3}", typeName, cellValue.toString(), e.getClass().getName(), e.getMessage()); } return result; }