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:org.nuxeo.ecm.platform.signature.web.sign.SignActions.java
protected SigningDisposition getDisposition(boolean originalIsPdf) { String disp;/*from ww w .ja va 2s.c o m*/ if (originalIsPdf) { disp = Framework.getProperty(SIGNATURE_DISPOSITION_PDF, SigningDisposition.ARCHIVE.name()); } else { disp = Framework.getProperty(SIGNATURE_DISPOSITION_NOTPDF, SigningDisposition.ATTACH.name()); } try { return Enum.valueOf(SigningDisposition.class, disp.toUpperCase()); } catch (RuntimeException e) { log.warn("Invalid signing disposition: " + disp); return SigningDisposition.ATTACH; } }
From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static void setColumnValue(final ResultSet rs, final StructAttributeReflect attr, final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path) throws Exception { KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0); String tabprefix = alias.getKey(); if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) { EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType()); switch (prim) { case ECharacter: String sv = rs.getString(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0)); }/*from w w w.j av a 2s . co m*/ break; case EShort: short shv = rs.getShort(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv); } break; case EInteger: int iv = rs.getInt(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv); } break; case ELong: long lv = rs.getLong(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv); } break; case EFloat: float fv = rs.getFloat(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv); } break; case EDouble: double dv = rs.getDouble(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv); } break; default: throw new Exception("Unsupported Data type [" + prim.name() + "]"); } } else if (attr.Convertor != null) { String value = rs.getString(tabprefix + "." + attr.Column); if (!rs.wasNull()) { attr.Convertor.load(entity, attr.Column, value); } } else if (attr.Field.getType().equals(String.class)) { String value = rs.getString(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), value); } } else if (attr.Field.getType().equals(Date.class)) { long value = rs.getLong(tabprefix + "." + attr.Column); if (!rs.wasNull()) { Date dt = new Date(value); PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dt); } } else if (attr.Field.getType().isEnum()) { String value = rs.getString(tabprefix + "." + attr.Column); if (!rs.wasNull()) { Class ecls = attr.Field.getType(); Object evalue = Enum.valueOf(ecls, value); PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), evalue); } } else if (attr.Reference != null) { Class<?> rt = Class.forName(attr.Reference.Class); Object obj = rt.newInstance(); if (!(obj instanceof AbstractEntity)) throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]"); AbstractEntity rentity = (AbstractEntity) obj; if (path.size() > 0) { path.peek().setKey(attr.Column); } KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>(); cls.setValue(rentity.getClass()); path.push(cls); setEntity(rentity, rs, gr, path); PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), rentity); path.pop(); } }
From source file:com.dumontierlab.pdb2rdf.Pdb2Rdf.java
private static void printRdf(final CommandLine cmd, final Map<String, Double> stats) { final File outDir = getOutputDirectory(cmd); final RDFWriter writer = getWriter(cmd); final ProgressMonitor monitor = getProgressMonitor(); Pdb2RdfInputIterator i = processInput(cmd); final int inputSize = i.size(); final AtomicInteger progressCount = new AtomicInteger(); ExecutorService pool = null;/*from w w w .ja va 2 s .co m*/ if (outDir != null) { pool = getThreadPool(cmd); } else { // if output is going to the STDOUT then we need to do process in // sequential mode. pool = Executors.newSingleThreadExecutor(); } final Object lock = new Object(); while (i.hasNext()) { final InputSource input = i.next(); pool.execute(new Runnable() { @Override public void run() { OutputStream out = System.out; PdbXmlParser parser = new PdbXmlParser(); PdbRdfModel model = null; try { if (cmd.hasOption("detailLevel")) { try { DetailLevel detailLevel = Enum.valueOf(DetailLevel.class, cmd.getOptionValue("detailLevel")); model = parser.parse(input, new PdbRdfModel(), detailLevel); } catch (IllegalArgumentException e) { LOG.fatal("Invalid argument value for detailLevel option", e); System.exit(1); } } else { model = parser.parse(input, new PdbRdfModel()); } // add the input file information model.addInputFileInformation(); // add the outputFile information(); model.addRDFFileInformation(); if (outDir != null) { File directory = new File(outDir, model.getPdbId().substring(1, 3)); synchronized (lock) { if (!directory.exists()) { directory.mkdir(); } } File file = new File(directory, model.getPdbId() + ".rdf.gz"); out = new GZIPOutputStream(new FileOutputStream(file)); } if (cmd.hasOption("format")) { if (cmd.getOptionValue("format").equalsIgnoreCase("NQUADs")) { Dataset ds = TDBFactory.createDataset(); ds.addNamedModel(model.getDatasetResource().toString(), model); StringWriter sw = new StringWriter(); RDFDataMgr.write(sw, ds, Lang.NQUADS); out.write(sw.toString().getBytes(Charset.forName("UTF-8"))); ds.close(); } } writer.write(model, out, null); if (stats != null) { updateStats(stats, model); } if (monitor != null) { monitor.setProgress(progressCount.incrementAndGet(), inputSize); } } catch (Exception e) { String id = null; if (model != null) { id = model.getPdbId(); } LOG.error("Unable to parse input for PDB: " + id, e); } finally { try { out.close(); } catch (IOException e) { LOG.error("Unable to close output stream", e); } } } }); } pool.shutdown(); while (!pool.isTerminated()) { try { pool.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { break; } } }
From source file:com.alliander.osgp.acceptancetests.adhocmanagement.SetTransitionSteps.java
@DomainStep("a set transition request for device (.*) with transitiontype (.*) and time (.*)") public void givenARequest(final String device, final String transitionType, final String time) throws DatatypeConfigurationException, ParseException { LOGGER.info("GIVEN: a set transition request for device {} with transitiontype {} and time {}.", new Object[] { device, transitionType, time }); this.setUp(); this.request = new SetTransitionRequest(); if (StringUtils.isNotBlank(transitionType)) { this.request.setTransitionType(Enum.valueOf(TransitionType.class, transitionType)); }//from w w w .java 2 s. c o m if (StringUtils.isNotBlank(time)) { this.request.setTime(DateUtils.convertToXMLGregorianCalendar(time, TIME_FORMAT)); } this.request.setDeviceIdentification(device); }
From source file:com.stevpet.sonar.plugins.dotnet.mscover.PropertiesHelper.java
public RunMode getRunMode() { String name = settings.getString(MSCOVER_MODE); if (StringUtils.isEmpty(name)) { return RunMode.SKIP; }// w w w . j av a 2 s .c o m RunMode runMode = RunMode.SKIP; try { runMode = Enum.valueOf(RunMode.class, name.toUpperCase()); } catch (IllegalArgumentException e) { String msg = "Invalid property value " + MSCOVER_MODE + "=" + name; Log.error(msg); throw new MsCoverException(msg); } return runMode; }
From source file:com.smartbear.postman.PostmanImporter.java
private static String createProjectName(String collectionName, List<? extends Project> projectList) { Class clazz;// ww w . j ava 2 s . c o m try { clazz = Class.forName("com.eviware.soapui.support.ModelItemNamer$NumberSuffixStrategy"); Method method = ModelItemNamer.class.getMethod("createName", String.class, Iterable.class, clazz); if (clazz.isEnum()) { return (String) method.invoke(null, collectionName, projectList, Enum.valueOf(clazz, "SUFFIX_WHEN_CONFLICT_FOUND")); } } catch (Throwable e) { logger.warn("Setting number suffix strategy is only supported in Ready! API", e); } return ModelItemNamer.createName(collectionName, projectList); }
From source file:com.microsoft.azure.management.compute.UsageOperationsImpl.java
/** * Lists compute usages for a subscription. * * @param location Required. The location upon which resource usage is * queried.//ww w . ja v a 2 s . c om * @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 List Usages operation response. */ @Override public ListUsagesResponse list(String location) throws IOException, ServiceException, URISyntaxException { // Validate if (location == null) { throw new NullPointerException("location"); } if (location != null && location.length() > 1000) { throw new IllegalArgumentException("location"); } if (Pattern.matches("^[-\\w\\._]+$", location) == false) { throw new IllegalArgumentException("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("location", location); CloudTracing.enter(invocationId, this, "listAsync", 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 + "/providers/"; url = url + "Microsoft.Compute"; url = url + "/locations/"; url = url + URLEncoder.encode(location, "UTF-8"); url = url + "/usages"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2015-06-15"); 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 ListUsagesResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ListUsagesResponse(); 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 valueArray = responseDoc.get("value"); if (valueArray != null && valueArray instanceof NullNode == false) { for (JsonNode valueValue : ((ArrayNode) valueArray)) { Usage usageInstance = new Usage(); result.getUsages().add(usageInstance); JsonNode unitValue = valueValue.get("unit"); if (unitValue != null && unitValue instanceof NullNode == false) { UsageUnit unitInstance; unitInstance = Enum.valueOf(UsageUnit.class, unitValue.getTextValue()); usageInstance.setUnit(unitInstance); } JsonNode currentValueValue = valueValue.get("currentValue"); if (currentValueValue != null && currentValueValue instanceof NullNode == false) { int currentValueInstance; currentValueInstance = currentValueValue.getIntValue(); usageInstance.setCurrentValue(currentValueInstance); } JsonNode limitValue = valueValue.get("limit"); if (limitValue != null && limitValue instanceof NullNode == false) { long limitInstance; limitInstance = limitValue.getLongValue(); usageInstance.setLimit(limitInstance); } JsonNode nameValue = valueValue.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { UsageName nameInstance = new UsageName(); usageInstance.setName(nameInstance); JsonNode valueValue2 = nameValue.get("value"); if (valueValue2 != null && valueValue2 instanceof NullNode == false) { String valueInstance; valueInstance = valueValue2.getTextValue(); nameInstance.setValue(valueInstance); } JsonNode localizedValueValue = nameValue.get("localizedValue"); if (localizedValueValue != null && localizedValueValue instanceof NullNode == false) { String localizedValueInstance; localizedValueInstance = localizedValueValue.getTextValue(); nameInstance.setLocalizedValue(localizedValueInstance); } } } } } } 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.rhq.enterprise.gui.event.EventHistoryUIBean.java
private EventSeverity[] getEventSeverity() { String[] severityNames = getSeverityFilter(); if (severityNames != null) { EventSeverity[] severities = new EventSeverity[severityNames.length]; for (int i = 0; i < severityNames.length; i++) { severities[i] = Enum.valueOf(EventSeverity.class, severityNames[i]); }// w ww. j av a2 s . co m return severities; } return null; }
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java
public static <E extends Enum<E>> E getEnum(Node node, String name, Class<E> enumType, E defaultValue) { try {//from w ww. ja v a2 s. co m Property prop = node.getProperty(name); return Enum.valueOf(enumType, prop.getString()); } catch (PathNotFoundException e) { return defaultValue; } catch (AccessDeniedException e) { log.debug("Access denied", e); throw new AccessControlException(e.getMessage()); } catch (RepositoryException e) { throw new MetadataRepositoryException("Failed to access property: " + name, e); } }
From source file:de.cosmocode.collections.utility.Convert.java
private static <E extends Enum<E>> E doIntoEnum(Object value, Class<E> enumType) { Preconditions.checkNotNull(enumType, "EnumType"); if (enumType.isInstance(value)) return enumType.cast(value); final Long ordinal = doIntoLong(value); if (ordinal == null) { final String name = doIntoString(value); if (name == null) return null; try {/*from ww w. ja va 2s. c om*/ return Enum.valueOf(enumType, name.toUpperCase()); } catch (IllegalArgumentException e) { return null; } } else { try { return Enums.valueOf(enumType, ordinal.intValue()); } catch (IndexOutOfBoundsException e) { return null; } } }