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.cedarsoft.serialization.jackson.AbstractJacksonSerializer.java
@Nonnull public <T extends Enum<T>> T deserializeEnum(@Nonnull Class<T> enumClass, @Nonnull JsonParser parser) throws IOException { return Enum.valueOf(enumClass, parser.getText()); }
From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Object fromJson(Class<?> clazz, Object json) throws JSONMappingException { if (json == null) return null; Object fromJson = null;/*from w w w . j a v a 2s . c om*/ if (clazz == null) { try { fromJson = JSONEntity.fromJson(json); } catch (JSONException e) { e.printStackTrace(); throw new JSONMappingException(e); } } else { Constructor<?> constructor; ; if (JSONEntity.class.isAssignableFrom(clazz)) { // A JSON Entity. Class<?> enclosingClass = clazz.getEnclosingClass(); if (enclosingClass != null && (clazz.getModifiers() & Modifier.STATIC) == 0) { // it's a non static inner class try { constructor = clazz.getDeclaredConstructor(enclosingClass, JSONObject.class); } catch (Exception e) { throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e); } try { /* we actually don't know the enclosing object... * this will be a problem with inner classes that * reference the enclosing class instance at * constructor time... although with json entities * that should not happen. */ fromJson = constructor.newInstance(null, json); } catch (Exception e) { throw new JSONMappingException(e); } } else { // static inner class try { constructor = clazz.getDeclaredConstructor(JSONObject.class); } catch (Exception e) { throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e); } try { fromJson = constructor.newInstance(json); } catch (Exception e) { throw new JSONMappingException("clazz = " + clazz.getName() + "; json = " + json.toString(), e); } } } else if (clazz.isEnum()) { try { fromJson = Enum.valueOf((Class<Enum>) clazz, json.toString()); } catch (Exception e) { fromJson = null; } } else { try { fromJson = JSONEntity.fromJson(json); } catch (JSONException e) { e.printStackTrace(); } } } if (clazz != null && !clazz.isAssignableFrom(fromJson.getClass())) throw new JSONMappingException("Was expeting a " + clazz.getName() + " but received a " + fromJson.getClass().getName() + " instead."); return fromJson; }
From source file:com.cedarsoft.serialization.jackson.AbstractJacksonSerializer.java
@Deprecated @Nonnull/*ww w.j a v a 2 s.com*/ public <T extends Enum<T>> T deserializeEnum(@Nonnull Class<T> enumClass, @Nonnull String propertyName, @Nonnull JacksonParserWrapper parser) throws IOException { parser.nextFieldValue(propertyName); return Enum.valueOf(enumClass, parser.getText()); }
From source file:com.microsoft.azure.management.websites.WebHostingPlanOperationsImpl.java
/** * Creates a new Web Hosting Plan or updates an existing one. (see * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/ * for more information)// w w w.ja va 2s .c om * * @param resourceGroupName Required. The name of the resource group. * @param parameters Required. Parameters supplied to the Create Server Farm * 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 Hosting Plan operation response. */ @Override public WebHostingPlanCreateOrUpdateResponse createOrUpdate(String resourceGroupName, WebHostingPlanCreateOrUpdateParameters parameters) throws IOException, ServiceException, URISyntaxException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getWebHostingPlan() == null) { throw new NullPointerException("parameters.WebHostingPlan"); } if (parameters.getWebHostingPlan().getLocation() == null) { throw new NullPointerException("parameters.WebHostingPlan.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("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 + "/serverFarms/"; if (parameters.getWebHostingPlan().getName() != null) { url = url + URLEncoder.encode(parameters.getWebHostingPlan().getName(), "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 webHostingPlanCreateOrUpdateParametersValue = objectMapper.createObjectNode(); requestDoc = webHostingPlanCreateOrUpdateParametersValue; if (parameters.getWebHostingPlan().getProperties() != null) { ObjectNode propertiesValue = objectMapper.createObjectNode(); ((ObjectNode) webHostingPlanCreateOrUpdateParametersValue).put("properties", propertiesValue); if (parameters.getWebHostingPlan().getProperties().getSku() != null) { ((ObjectNode) propertiesValue).put("sku", parameters.getWebHostingPlan().getProperties().getSku().toString()); } ((ObjectNode) propertiesValue).put("numberOfWorkers", parameters.getWebHostingPlan().getProperties().getNumberOfWorkers()); if (parameters.getWebHostingPlan().getProperties().getWorkerSize() != null) { ((ObjectNode) propertiesValue).put("workerSize", parameters.getWebHostingPlan().getProperties().getWorkerSize().toString()); } if (parameters.getWebHostingPlan().getProperties().getAdminSiteName() != null) { ((ObjectNode) propertiesValue).put("adminSiteName", parameters.getWebHostingPlan().getProperties().getAdminSiteName()); } } if (parameters.getWebHostingPlan().getId() != null) { ((ObjectNode) webHostingPlanCreateOrUpdateParametersValue).put("id", parameters.getWebHostingPlan().getId()); } if (parameters.getWebHostingPlan().getName() != null) { ((ObjectNode) webHostingPlanCreateOrUpdateParametersValue).put("name", parameters.getWebHostingPlan().getName()); } ((ObjectNode) webHostingPlanCreateOrUpdateParametersValue).put("location", parameters.getWebHostingPlan().getLocation()); if (parameters.getWebHostingPlan().getTags() != null) { ObjectNode tagsDictionary = objectMapper.createObjectNode(); for (Map.Entry<String, String> entry : parameters.getWebHostingPlan().getTags().entrySet()) { String tagsKey = entry.getKey(); String tagsValue = entry.getValue(); ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue); } ((ObjectNode) webHostingPlanCreateOrUpdateParametersValue).put("tags", tagsDictionary); } if (parameters.getWebHostingPlan().getType() != null) { ((ObjectNode) webHostingPlanCreateOrUpdateParametersValue).put("type", parameters.getWebHostingPlan().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 WebHostingPlanCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebHostingPlanCreateOrUpdateResponse(); JsonNode responseDoc = null; String responseDocContent = IOUtils.toString(responseContent); if (responseDocContent == null == false && responseDocContent.length() > 0) { responseDoc = objectMapper.readTree(responseDocContent); } JsonNode serverFarmValue = responseDoc.get("ServerFarm"); if (serverFarmValue != null && serverFarmValue instanceof NullNode == false) { WebHostingPlanCreateOrUpdateResponse serverFarmInstance = new WebHostingPlanCreateOrUpdateResponse(); WebHostingPlan webHostingPlanInstance = new WebHostingPlan(); result.setWebHostingPlan(webHostingPlanInstance); JsonNode propertiesValue2 = serverFarmValue.get("properties"); if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) { WebHostingPlanProperties propertiesInstance = new WebHostingPlanProperties(); webHostingPlanInstance.setProperties(propertiesInstance); 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 numberOfWorkersValue = propertiesValue2.get("numberOfWorkers"); if (numberOfWorkersValue != null && numberOfWorkersValue instanceof NullNode == false) { int numberOfWorkersInstance; numberOfWorkersInstance = numberOfWorkersValue.getIntValue(); propertiesInstance.setNumberOfWorkers(numberOfWorkersInstance); } JsonNode workerSizeValue = propertiesValue2.get("workerSize"); if (workerSizeValue != null && workerSizeValue instanceof NullNode == false) { WorkerSizeOptions workerSizeInstance; workerSizeInstance = Enum.valueOf(WorkerSizeOptions.class, workerSizeValue.getTextValue()); propertiesInstance.setWorkerSize(workerSizeInstance); } JsonNode adminSiteNameValue = propertiesValue2.get("adminSiteName"); if (adminSiteNameValue != null && adminSiteNameValue instanceof NullNode == false) { String adminSiteNameInstance; adminSiteNameInstance = adminSiteNameValue.getTextValue(); propertiesInstance.setAdminSiteName(adminSiteNameInstance); } } JsonNode idValue = serverFarmValue.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); webHostingPlanInstance.setId(idInstance); } JsonNode nameValue = serverFarmValue.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); webHostingPlanInstance.setName(nameInstance); } JsonNode locationValue = serverFarmValue.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); webHostingPlanInstance.setLocation(locationInstance); } JsonNode tagsSequenceElement = ((JsonNode) serverFarmValue.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(); webHostingPlanInstance.getTags().put(tagsKey2, tagsValue2); } } JsonNode typeValue = serverFarmValue.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:alma.acs.nc.sm.generic.AcsScxmlEngine.java
/** * Gets the signals that would trigger transitions for the current state. * <p>/*from w w w. j a v a 2 s . c o m*/ * When actually sending such signals later on, the SM may have moved to a different state. * To prevent this, you can synchronize on this AcsScxmlEngine, which will block concurrent calls to {@link #fireSignal(Enum)}. * <p> * This method can be useful for displaying applicable signals in a GUI, * or to reject signals (with exception etc) that do not "fit" the current state * (while normally such signals would be silently ignored). * The latter gets used in {@link #fireSignalWithErrorFeedback(Enum)}. * * @see org.apache.commons.scxml.semantics.SCXMLSemanticsImpl#enumerateReachableTransitions(SCXML, Step, ErrorReporter) */ public synchronized Set<S> getApplicableSignals() { Set<String> events = new HashSet<String>(); @SuppressWarnings("unchecked") Set<TransitionTarget> stateSet = new HashSet<TransitionTarget>(exec.getCurrentStatus().getStates()); LinkedList<TransitionTarget> todoList = new LinkedList<TransitionTarget>(stateSet); while (!todoList.isEmpty()) { TransitionTarget tt = todoList.removeFirst(); @SuppressWarnings("unchecked") List<Transition> transitions = tt.getTransitionsList(); for (Transition t : transitions) { String event = t.getEvent(); events.add(event); } TransitionTarget parentTT = tt.getParent(); if (parentTT != null && !stateSet.contains(parentTT)) { stateSet.add(parentTT); todoList.addLast(parentTT); } } // convert signal names to enum constants Set<S> ret = new HashSet<S>(); for (String signalName : events) { S signal = Enum.valueOf(signalType, signalName); ret.add(signal); } return ret; }
From source file:com.l2jfree.gameserver.templates.StatsSet.java
/** * Returns an enumeration of <T> from the set * /*w w w .ja va2 s . co m*/ * @param <T> : Class of the enumeration returned * @param name : String designating the key in the set * @param enumClass : Class designating the class of the value associated with the key in the set * @return Enum<T> */ @SuppressWarnings("unchecked") public final <T extends Enum<T>> T getEnum(String name, Class<T> enumClass) { Object val = get(name); if (val == null) throw new IllegalArgumentException( "Enum value of type " + enumClass.getName() + " required, but not specified"); if (enumClass.isInstance(val)) return (T) val; try { return Enum.valueOf(enumClass, String.valueOf(val)); } catch (Exception e) { throw new IllegalArgumentException( "Enum value of type " + enumClass.getName() + "required, but found: " + val); } }
From source file:org.powertac.logtool.common.DomainObjectReader.java
private Object resolveArg(Type type, String arg) throws MissingDomainObject { // type can be null in a few cases - nothing to be done about it? if (null == type) { return null; }// w w w . j a v a 2s. c o m // check for non-parameterized types if (type instanceof Class) { Class<?> clazz = (Class<?>) type; if (clazz.isEnum()) { return Enum.valueOf((Class<Enum>) type, arg); } else { return resolveSimpleArg(clazz, arg); } } // check for collection, denoted by leading ( if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Class<?> clazz = (Class<?>) ptype.getRawType(); boolean isCollection = false; if (clazz.equals(Collection.class)) isCollection = true; else { Class<?>[] ifs = clazz.getInterfaces(); for (Class<?> ifc : ifs) { if (ifc.equals(Collection.class)) { isCollection = true; break; } } } if (isCollection) { // expect arg to start with "(" log.debug("processing collection " + clazz.getName()); if (arg.charAt(0) != '(') { log.error("Collection arg " + arg + " does not start with paren"); return null; } // extract element type and resolve recursively Type[] tas = ptype.getActualTypeArguments(); if (1 == tas.length) { Class<?> argClazz = (Class<?>) tas[0]; // create an instance of the collection Collection<Object> coll; // resolve interfaces into actual classes if (clazz.isInterface()) clazz = ifImplementors.get(clazz); try { coll = (Collection<Object>) clazz.newInstance(); } catch (Exception e) { log.error("Exception creating collection: " + e.toString()); return null; } // at this point, we can split the string and resolve recursively String body = arg.substring(1, arg.indexOf(')')); String[] items = body.split(","); for (String item : items) { coll.add(resolveSimpleArg(argClazz, item)); } return coll; } } } // if we get here, no resolution log.error("unresolved arg: type = " + type + ", arg = " + arg); return null; }
From source file:org.kalypsodeegree_impl.model.feature.Feature_Impl.java
/** * Returns a property that is represented by an enumeration. *//*w w w . ja v a 2 s .c o m*/ protected <T extends Enum<T>> T getEnumProperty(final QName propertyName, final Class<T> enumType, final T defaultValue) { final String value = getProperty(propertyName, String.class); if (StringUtils.isBlank(value)) return defaultValue; try { return Enum.valueOf(enumType, value); } catch (final IllegalArgumentException e) { e.printStackTrace(); return defaultValue; } }
From source file:org.apache.hadoop.hbase.util.FanOutOneBlockAsyncDFSOutputSaslHelper.java
private static CipherHelper 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"); final Method convertCipherOptionsMethod = PBHelper.class.getMethod("convertCipherOptions", List.class); final Method convertCipherOptionProtosMethod = PBHelper.class.getMethod("convertCipherOptionProtos", List.class); final Method addAllCipherOptionMethod = DataTransferEncryptorMessageProto.Builder.class .getMethod("addAllCipherOption", Iterable.class); final Method getCipherOptionListMethod = DataTransferEncryptorMessageProto.class .getMethod("getCipherOptionList"); return new CipherHelper() { @Override//from www . j a v a 2s . c o m 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:org.apache.hadoop.hive.ql.metadata.Table.java
public TableType getTableType() { return Enum.valueOf(TableType.class, tTable.getTableType()); }