List of usage examples for org.apache.commons.lang3.math NumberUtils toLong
public static long toLong(final String str)
Convert a String
to a long
, returning zero
if the conversion fails.
If the string is null
, zero
is returned.
NumberUtils.toLong(null) = 0L NumberUtils.toLong("") = 0L NumberUtils.toLong("1") = 1L
From source file:org.apache.syncope.client.console.panels.search.SearchUtils.java
public static String buildFIQL(final List<SearchClause> clauses, final AbstractFiqlSearchConditionBuilder builder, final Map<String, PlainSchemaTO> availableSchemaTypes) { LOG.debug("Generating FIQL from List<SearchClause>: {}", clauses); CompleteCondition prevCondition;//w w w . j av a 2s .com CompleteCondition condition = null; boolean notTheFirst = false; for (SearchClause clause : clauses) { prevCondition = condition; if (clause.getType() != null) { String value = clause.getValue() == null ? null : clause.getValue().replace(",", "%252C").replace(";", "%253B"); switch (clause.getType()) { case GROUP_MEMBER: switch (clause.getComparator()) { case EQUALS: condition = ((GroupFiqlSearchConditionBuilder) builder).withMembers(value); break; case NOT_EQUALS: condition = ((GroupFiqlSearchConditionBuilder) builder).withoutMembers(value); break; default: } break; case GROUP_MEMBERSHIP: if (StringUtils.isNotBlank(clause.getProperty())) { String groupKey = clause.getProperty(); if (builder instanceof UserFiqlSearchConditionBuilder) { condition = clause.getComparator() == SearchClause.Comparator.EQUALS ? ((UserFiqlSearchConditionBuilder) builder).inGroups(groupKey) : ((UserFiqlSearchConditionBuilder) builder).notInGroups(groupKey); } else { condition = clause.getComparator() == SearchClause.Comparator.EQUALS ? ((AnyObjectFiqlSearchConditionBuilder) builder).inGroups(groupKey) : ((AnyObjectFiqlSearchConditionBuilder) builder).notInGroups(groupKey); } } break; case RESOURCE: if (StringUtils.isNotBlank(clause.getProperty())) { condition = clause.getComparator() == SearchClause.Comparator.EQUALS ? builder.hasResources(clause.getProperty()) : builder.hasNotResources(clause.getProperty()); } break; case ATTRIBUTE: if (StringUtils.isNotBlank(clause.getProperty())) { boolean isLong = false; boolean isDouble = false; if (availableSchemaTypes.get(clause.getProperty()) != null) { isLong = availableSchemaTypes.get(clause.getProperty()) .getType() == AttrSchemaType.Long; isDouble = availableSchemaTypes.get(clause.getProperty()) .getType() == AttrSchemaType.Double; } SyncopeProperty property = builder.is(clause.getProperty()); switch (clause.getComparator()) { case IS_NULL: condition = builder.isNull(clause.getProperty()); break; case IS_NOT_NULL: condition = builder.isNotNull(clause.getProperty()); break; case LESS_THAN: condition = isLong ? property.lessThan(NumberUtils.toLong(value)) : isDouble ? property.lessThan(NumberUtils.toDouble(value)) : property.lexicalBefore(value); break; case LESS_OR_EQUALS: condition = isLong ? property.lessOrEqualTo(NumberUtils.toLong(value)) : isDouble ? property.lessOrEqualTo(NumberUtils.toDouble(value)) : property.lexicalNotAfter(value); break; case GREATER_THAN: condition = isLong ? property.greaterThan(NumberUtils.toLong(value)) : isDouble ? property.greaterThan(NumberUtils.toDouble(value)) : property.lexicalAfter(value); break; case GREATER_OR_EQUALS: condition = isLong ? property.greaterOrEqualTo(NumberUtils.toLong(value)) : isDouble ? property.greaterOrEqualTo(NumberUtils.toDouble(value)) : property.lexicalNotBefore(value); break; case NOT_EQUALS: condition = property.notEqualTolIgnoreCase(value); break; case EQUALS: condition = isLong ? property.equalTo(NumberUtils.toLong(value)) : isDouble ? property.equalTo(NumberUtils.toDouble(value)) : property.equalToIgnoreCase(value); break; default: condition = property.equalToIgnoreCase(value); break; } } break; case ROLE_MEMBERSHIP: if (StringUtils.isNotBlank(clause.getProperty())) { switch (clause.getComparator()) { case EQUALS: condition = ((UserFiqlSearchConditionBuilder) builder).inRoles(clause.getProperty()); break; case NOT_EQUALS: condition = ((UserFiqlSearchConditionBuilder) builder).notInRoles(clause.getProperty()); break; default: break; } } break; case RELATIONSHIP: if (StringUtils.isNotBlank(clause.getProperty())) { if (builder instanceof UserFiqlSearchConditionBuilder) { switch (clause.getComparator()) { case IS_NOT_NULL: condition = ((UserFiqlSearchConditionBuilder) builder) .inRelationshipTypes(clause.getProperty()); break; case IS_NULL: condition = ((UserFiqlSearchConditionBuilder) builder) .notInRelationshipTypes(clause.getProperty()); break; case EQUALS: condition = ((UserFiqlSearchConditionBuilder) builder).inRelationships(value); break; case NOT_EQUALS: condition = ((UserFiqlSearchConditionBuilder) builder).notInRelationships(value); break; default: break; } } else { switch (clause.getComparator()) { case IS_NOT_NULL: condition = ((AnyObjectFiqlSearchConditionBuilder) builder) .inRelationshipTypes(clause.getProperty()); break; case IS_NULL: condition = ((AnyObjectFiqlSearchConditionBuilder) builder) .notInRelationshipTypes(clause.getProperty()); break; case EQUALS: condition = ((AnyObjectFiqlSearchConditionBuilder) builder).inRelationships(value); break; case NOT_EQUALS: condition = ((AnyObjectFiqlSearchConditionBuilder) builder) .notInRelationships(value); break; default: break; } } } break; default: break; } } if (notTheFirst) { if (clause.getOperator() == SearchClause.Operator.AND) { condition = builder.and(prevCondition, condition); } if (clause.getOperator() == SearchClause.Operator.OR) { condition = builder.or(prevCondition, condition); } } notTheFirst = true; } String fiql = condition == null ? null : condition.query(); LOG.debug("Generated FIQL: {}", fiql); return fiql; }
From source file:org.apache.syncope.client.console.wicket.markup.html.form.AjaxSpinnerFieldPanel.java
@Override public AjaxSpinnerFieldPanel<T> setNewModel(final List<Serializable> list) { setNewModel(new Model<T>() { private static final long serialVersionUID = 527651414610325237L; @Override/*from w w w . j av a 2 s . com*/ public T getObject() { T value = null; if (list != null && !list.isEmpty() && list.get(0) != null && StringUtils.isNotBlank(list.get(0).toString())) { value = reference.equals(Integer.class) ? reference.cast(NumberUtils.toInt(list.get(0).toString())) : reference.equals(Long.class) ? reference.cast(NumberUtils.toLong(list.get(0).toString())) : reference.equals(Short.class) ? reference.cast(NumberUtils.toShort(list.get(0).toString())) : reference.equals(Float.class) ? reference.cast(NumberUtils.toFloat(list.get(0).toString())) : reference.equals(byte.class) ? reference.cast( NumberUtils.toByte(list.get(0).toString())) : reference.cast( NumberUtils.toDouble(list.get(0).toString())); } return value; } @Override public void setObject(final T object) { list.clear(); if (object != null) { list.add(object.toString()); } } }); return this; }
From source file:org.apache.syncope.client.console.wicket.markup.html.form.SpinnerFieldPanel.java
@Override public SpinnerFieldPanel<T> setNewModel(final List<Serializable> list) { setNewModel(new Model<T>() { private static final long serialVersionUID = 527651414610325237L; @Override/*from w w w . ja v a 2s. c om*/ public T getObject() { T value = null; if (list != null && !list.isEmpty() && StringUtils.hasText(list.get(0).toString())) { value = reference.equals(Integer.class) ? reference.cast(NumberUtils.toInt(list.get(0).toString())) : reference.equals(Long.class) ? reference.cast(NumberUtils.toLong(list.get(0).toString())) : reference.equals(Short.class) ? reference.cast(NumberUtils.toShort(list.get(0).toString())) : reference.equals(Float.class) ? reference.cast(NumberUtils.toFloat(list.get(0).toString())) : reference.equals(byte.class) ? reference.cast( NumberUtils.toByte(list.get(0).toString())) : reference.cast( NumberUtils.toDouble(list.get(0).toString())); } return value; } @Override public void setObject(final T object) { list.clear(); if (object != null) { list.add(object.toString()); } } }); return this; }
From source file:org.apache.syncope.console.pages.ApprovalModalPage.java
public ApprovalModalPage(final PageReference pageRef, final ModalWindow window, final WorkflowFormTO formTO) { super();// w w w .ja va 2s. co m IModel<List<WorkflowFormPropertyTO>> formProps = new LoadableDetachableModel<List<WorkflowFormPropertyTO>>() { private static final long serialVersionUID = 3169142472626817508L; @Override protected List<WorkflowFormPropertyTO> load() { return formTO.getProperties(); } }; final ListView<WorkflowFormPropertyTO> propView = new AltListView<WorkflowFormPropertyTO>("propView", formProps) { private static final long serialVersionUID = 9101744072914090143L; @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected void populateItem(final ListItem<WorkflowFormPropertyTO> item) { final WorkflowFormPropertyTO prop = item.getModelObject(); Label label = new Label("key", prop.getName() == null ? prop.getId() : prop.getName()); item.add(label); FieldPanel field; switch (prop.getType()) { case Boolean: field = new AjaxDropDownChoicePanel("value", label.getDefaultModelObjectAsString(), new Model<Boolean>(Boolean.valueOf(prop.getValue()))) .setChoices(Arrays.asList(new String[] { "Yes", "No" })); break; case Date: SimpleDateFormat df = StringUtils.isNotBlank(prop.getDatePattern()) ? new SimpleDateFormat(prop.getDatePattern()) : new SimpleDateFormat(); Date parsedDate = null; if (StringUtils.isNotBlank(prop.getValue())) { try { parsedDate = df.parse(prop.getValue()); } catch (ParseException e) { LOG.error("Unparsable date: {}", prop.getValue(), e); } } field = new DateTimeFieldPanel("value", label.getDefaultModelObjectAsString(), new Model<Date>(parsedDate), df.toLocalizedPattern()); break; case Enum: MapChoiceRenderer<String, String> enumCR = new MapChoiceRenderer<String, String>( prop.getEnumValues()); field = new AjaxDropDownChoicePanel("value", label.getDefaultModelObjectAsString(), new Model(prop.getValue())).setChoiceRenderer(enumCR).setChoices(new Model() { private static final long serialVersionUID = -858521070366432018L; @Override public Serializable getObject() { return new ArrayList<String>(prop.getEnumValues().keySet()); } }); break; case Long: field = new SpinnerFieldPanel<Long>("value", label.getDefaultModelObjectAsString(), Long.class, new Model<Long>(NumberUtils.toLong(prop.getValue())), null, null); break; case String: default: field = new AjaxTextFieldPanel("value", PARENT_PATH, new Model<String>(prop.getValue())); break; } field.setReadOnly(!prop.isWritable()); if (prop.isRequired()) { field.addRequiredLabel(); } item.add(field); } }; final AjaxButton userDetails = new IndicatingAjaxButton("userDetails", new Model<String>(getString("userDetails"))) { private static final long serialVersionUID = -4804368561204623354L; @Override protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) { editUserWin.setPageCreator(new ModalWindow.PageCreator() { private static final long serialVersionUID = -7834632442532690940L; @Override public Page createPage() { return new ViewUserModalPage(ApprovalModalPage.this.getPageReference(), editUserWin, userRestClient.read(formTO.getUserId())) { private static final long serialVersionUID = -2819994749866481607L; @Override protected void closeAction(final AjaxRequestTarget target, final Form form) { setResponsePage(ApprovalModalPage.this); } }; } }); editUserWin.show(target); } }; MetaDataRoleAuthorizationStrategy.authorize(userDetails, ENABLE, xmlRolesReader.getAllAllowedRoles("Users", "read")); final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<String>(getString(SUBMIT))) { private static final long serialVersionUID = -958724007591692537L; @Override protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) { Map<String, WorkflowFormPropertyTO> props = formTO.getPropertyMap(); for (int i = 0; i < propView.size(); i++) { @SuppressWarnings("unchecked") ListItem<WorkflowFormPropertyTO> item = (ListItem<WorkflowFormPropertyTO>) propView.get(i); String input = ((FieldPanel) item.get("value")).getField().getInput(); if (!props.containsKey(item.getModelObject().getId())) { props.put(item.getModelObject().getId(), new WorkflowFormPropertyTO()); } if (item.getModelObject().isWritable()) { switch (item.getModelObject().getType()) { case Boolean: props.get(item.getModelObject().getId()).setValue(String.valueOf("0".equals(input))); break; case Date: case Enum: case String: case Long: default: props.get(item.getModelObject().getId()).setValue(input); break; } } } formTO.setProperties(props.values()); try { restClient.submitForm(formTO); ((Todo) pageRef.getPage()).setModalResult(true); window.close(target); } catch (SyncopeClientException e) { error(getString(Constants.ERROR) + ": " + e.getMessage()); LOG.error("While submitting form {}", formTO, e); feedbackPanel.refresh(target); } } @Override protected void onError(final AjaxRequestTarget target, final Form<?> form) { feedbackPanel.refresh(target); } }; final AjaxButton cancel = new IndicatingAjaxButton(CANCEL, new ResourceModel(CANCEL)) { private static final long serialVersionUID = -958724007591692537L; @Override protected void onSubmit(final AjaxRequestTarget target, final Form form) { window.close(target); } @Override protected void onError(final AjaxRequestTarget target, final Form form) { // nothing } }; cancel.setDefaultFormProcessing(false); Form form = new Form(FORM); form.add(propView); form.add(userDetails); form.add(submit); form.add(cancel); MetaDataRoleAuthorizationStrategy.authorize(form, ENABLE, xmlRolesReader.getAllAllowedRoles("Approval", SUBMIT)); editUserWin = new ModalWindow("editUserWin"); editUserWin.setCssClassName(ModalWindow.CSS_CLASS_GRAY); editUserWin.setInitialHeight(USER_WIN_HEIGHT); editUserWin.setInitialWidth(USER_WIN_WIDTH); editUserWin.setCookieName("edit-user-modal"); add(editUserWin); add(form); }
From source file:org.apache.syncope.console.pages.panels.AbstractSearchPanel.java
public String buildFIQL() { LOG.debug("Generating FIQL from List<SearchClause>: {}", searchClauses); if (searchClauses.isEmpty() || searchClauses.get(0).getType() == null) { return StringUtils.EMPTY; }/*from w ww. java2s. c o m*/ SyncopeFiqlSearchConditionBuilder builder = getSearchConditionBuilder(); CompleteCondition prevCondition; CompleteCondition condition = null; for (int i = 0; i < searchClauses.size(); i++) { prevCondition = condition; switch (searchClauses.get(i).getType()) { case ENTITLEMENT: condition = searchClauses.get(i).getComparator() == SearchClause.Comparator.EQUALS ? ((RoleFiqlSearchConditionBuilder) builder) .hasEntitlements(searchClauses.get(i).getProperty()) : ((RoleFiqlSearchConditionBuilder) builder) .hasNotEntitlements(searchClauses.get(i).getProperty()); break; case MEMBERSHIP: Long roleId = NumberUtils.toLong(searchClauses.get(i).getProperty().split(" ")[0]); condition = searchClauses.get(i).getComparator() == SearchClause.Comparator.EQUALS ? ((UserFiqlSearchConditionBuilder) builder).hasRoles(roleId) : ((UserFiqlSearchConditionBuilder) builder).hasNotRoles(roleId); break; case RESOURCE: condition = searchClauses.get(i).getComparator() == SearchClause.Comparator.EQUALS ? builder.hasResources(searchClauses.get(i).getProperty()) : builder.hasNotResources(searchClauses.get(i).getProperty()); break; case ATTRIBUTE: SyncopeProperty property = builder.is(searchClauses.get(i).getProperty()); switch (searchClauses.get(i).getComparator()) { case IS_NULL: condition = builder.isNull(searchClauses.get(i).getProperty()); break; case IS_NOT_NULL: condition = builder.isNotNull(searchClauses.get(i).getProperty()); break; case LESS_THAN: condition = StringUtils.isNumeric(searchClauses.get(i).getProperty()) ? property.lessThan(NumberUtils.toDouble(searchClauses.get(i).getValue())) : property.lexicalBefore(searchClauses.get(i).getValue()); break; case LESS_OR_EQUALS: condition = StringUtils.isNumeric(searchClauses.get(i).getProperty()) ? property.lessOrEqualTo(NumberUtils.toDouble(searchClauses.get(i).getValue())) : property.lexicalNotAfter(searchClauses.get(i).getValue()); break; case GREATER_THAN: condition = StringUtils.isNumeric(searchClauses.get(i).getProperty()) ? property.greaterThan(NumberUtils.toDouble(searchClauses.get(i).getValue())) : property.lexicalAfter(searchClauses.get(i).getValue()); break; case GREATER_OR_EQUALS: condition = StringUtils.isNumeric(searchClauses.get(i).getProperty()) ? property.greaterOrEqualTo(NumberUtils.toDouble(searchClauses.get(i).getValue())) : property.lexicalNotBefore(searchClauses.get(i).getValue()); break; case NOT_EQUALS: condition = property.notEqualTo(searchClauses.get(i).getValue()); break; case EQUALS: default: condition = property.equalTo(searchClauses.get(i).getValue()); break; } default: break; } if (i > 0) { if (searchClauses.get(i).getOperator() == SearchClause.Operator.AND) { condition = builder.and(prevCondition, condition); } if (searchClauses.get(i).getOperator() == SearchClause.Operator.OR) { condition = builder.or(prevCondition, condition); } } } String fiql = condition == null ? StringUtils.EMPTY : condition.query(); LOG.debug("Generated FIQL: {}", fiql); return fiql; }
From source file:org.bonitasoft.engine.api.impl.LoginAPIImpl.java
@Override @CustomTransactions/*from ww w . ja v a2 s .c o m*/ @AvailableWhenTenantIsPaused public APISession login(final Map<String, Serializable> credentials) throws LoginException { checkCredentialsAreNotNullOrEmpty(credentials); try { final Long tenantId = NumberUtils .isNumber(String.valueOf(credentials.get(AuthenticationConstants.BASIC_TENANT_ID))) ? NumberUtils.toLong( String.valueOf(credentials.get(AuthenticationConstants.BASIC_TENANT_ID))) : null; return loginInternal(tenantId, credentials); } catch (final LoginException e) { throw e; } catch (final Exception e) { throw new LoginException(e); } }
From source file:org.efaps.admin.index.Indexer.java
/** * Index or reindex a given list of instances. The given instances m,ust be * all of the same type!//from www. j a v a 2 s . c o m * * @param _context the _context * @param _instances the instances * @throws EFapsException the e faps exception */ public static void index(final IndexContext _context, final List<Instance> _instances) throws EFapsException { if (CollectionUtils.isNotEmpty(_instances)) { final Company currentCompany = Context.getThreadContext().getCompany(); final String currentLanguage = Context.getThreadContext().getLanguage(); Context.getThreadContext().setCompany(Company.get(_context.getCompanyId())); Context.getThreadContext().setLanguage(_context.getLanguage()); final IndexWriterConfig config = new IndexWriterConfig(_context.getAnalyzer()); try (IndexWriter writer = new IndexWriter(_context.getDirectory(), config); TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(_context.getTaxonomyDirectory());) { final IndexDefinition def = IndexDefinition.get(_instances.get(0).getType().getUUID()); final MultiPrintQuery multi = new MultiPrintQuery(_instances); for (final IndexField field : def.getFields()) { multi.addSelect(field.getSelect()); } Attribute createdAttr = null; if (!_instances.get(0).getType().getAttributes(CreatedType.class).isEmpty()) { createdAttr = _instances.get(0).getType().getAttributes(CreatedType.class).iterator().next(); multi.addAttribute(createdAttr); } multi.addMsgPhrase(def.getMsgPhrase()); multi.executeWithoutAccessCheck(); while (multi.next()) { final String oid = multi.getCurrentInstance().getOid(); final String type = multi.getCurrentInstance().getType().getLabel(); final DateTime created; if (createdAttr == null) { created = new DateTime(); } else { created = multi.getAttribute(createdAttr); } final Document doc = new Document(); doc.add(new FacetField(Dimension.DIMTYPE.name(), type)); doc.add(new FacetField(Dimension.DIMCREATED.name(), String.valueOf(created.getYear()), String.format("%02d", created.getMonthOfYear()))); doc.add(new StringField(Key.OID.name(), oid, Store.YES)); doc.add(new TextField(DBProperties.getProperty("index.Type"), type, Store.YES)); doc.add(new NumericDocValuesField(Key.CREATED.name(), created.getMillis())); doc.add(new StringField(Key.CREATEDSTR.name(), DateTools.dateToString(created.toDate(), DateTools.Resolution.DAY), Store.NO)); final StringBuilder allBldr = new StringBuilder().append(type).append(" "); for (final IndexField field : def.getFields()) { final String name = DBProperties.getProperty(field.getKey()); Object value = multi.getSelect(field.getSelect()); if (value != null) { if (StringUtils.isNoneEmpty(field.getTransform())) { final Class<?> clazz = Class.forName(field.getTransform(), false, EFapsClassLoader.getInstance()); final ITransformer transformer = (ITransformer) clazz.newInstance(); value = transformer.transform(value); } switch (field.getFieldType()) { case LONG: long val = 0; if (value instanceof String) { val = NumberUtils.toLong((String) value); } else if (value instanceof Number) { val = ((Number) value).longValue(); } doc.add(new LongField(name, val, Store.YES)); allBldr.append(value).append(" "); break; case SEARCHLONG: long val2 = 0; if (value instanceof String) { val2 = NumberUtils.toLong((String) value); } else if (value instanceof Number) { val2 = ((Number) value).longValue(); } doc.add(new LongField(name, val2, Store.NO)); allBldr.append(value).append(" "); break; case STRING: doc.add(new StringField(name, String.valueOf(value), Store.YES)); allBldr.append(value).append(" "); break; case SEARCHSTRING: doc.add(new StringField(name, String.valueOf(value), Store.NO)); allBldr.append(value).append(" "); break; case TEXT: doc.add(new TextField(name, String.valueOf(value), Store.YES)); allBldr.append(value).append(" "); break; case SEARCHTEXT: doc.add(new TextField(name, String.valueOf(value), Store.NO)); allBldr.append(value).append(" "); break; case STORED: doc.add(new StoredField(name, String.valueOf(value))); allBldr.append(value).append(" "); break; default: break; } } } doc.add(new StoredField(Key.MSGPHRASE.name(), multi.getMsgPhrase(def.getMsgPhrase()))); doc.add(new TextField(Key.ALL.name(), allBldr.toString(), Store.NO)); writer.updateDocument(new Term(Key.OID.name(), oid), Index.getFacetsConfig().build(taxonomyWriter, doc)); LOG.debug("Add Document: {}", doc); } writer.close(); taxonomyWriter.close(); } catch (final IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new EFapsException(Indexer.class, "IOException", e); } finally { Context.getThreadContext().setCompany(currentCompany); Context.getThreadContext().setLanguage(currentLanguage); } } }
From source file:org.manalith.ircbot.plugin.tweetreader.TweetReader.java
private Status getStatus(String url, UrlType type) throws TwitterException { Status stat = null;//from w w w .ja va 2s . com String[] urlArray = url.split("\\/"); switch (type) { case TweetURL: case PhotoURL: int statusIdIdx = 0; for (; statusIdIdx < urlArray.length; statusIdIdx++) if (urlArray[statusIdIdx++].equals("status")) break; long tweetId = NumberUtils.toLong(urlArray[statusIdIdx]); stat = tweet.showStatus(tweetId); if (stat == null) return null; break; case UserURL: String screenName = urlArray[urlArray.length - 1]; ResponseList<Status> resp = tweet.getUserTimeline(screenName); if (resp.size() == 0) return null; stat = resp.get(0); break; } return stat; }
From source file:org.mariotaku.twidere.fragment.card.CardPollFragment.java
private void displayPoll(final ParcelableCardEntity card, final ParcelableStatus status) { final Context context = getContext(); if (card == null || status == null || context == null) return;/*from ww w. ja v a 2s . c om*/ mCard = card; final int choicesCount = getChoicesCount(card); int votesSum = 0; final boolean countsAreFinal = ParcelableCardEntityUtils.getAsBoolean(card, "counts_are_final", false); final int selectedChoice = ParcelableCardEntityUtils.getAsInteger(card, "selected_choice", -1); final Date endDatetimeUtc = ParcelableCardEntityUtils.getAsDate(card, "end_datetime_utc", new Date()); final boolean hasChoice = selectedChoice != -1; final boolean isMyPoll = status.account_key.equals(status.user_key); final boolean showResult = countsAreFinal || isMyPoll || hasChoice; for (int i = 0; i < choicesCount; i++) { final int choiceIndex = i + 1; votesSum += ParcelableCardEntityUtils.getAsInteger(card, "choice" + choiceIndex + "_count", 0); } final View.OnClickListener clickListener = new View.OnClickListener() { private boolean clickedChoice; @Override public void onClick(View v) { if (hasChoice || clickedChoice) return; for (int i = 0, j = mPollContainer.getChildCount(); i < j; i++) { final View pollItem = mPollContainer.getChildAt(i); pollItem.setClickable(false); clickedChoice = true; final RadioButton choiceRadioButton = (RadioButton) pollItem.findViewById(R.id.choice_button); final boolean checked = v == pollItem; choiceRadioButton.setChecked(checked); if (checked) { final CardDataMap cardData = new CardDataMap(); cardData.putLong("original_tweet_id", NumberUtils.toLong(status.id)); cardData.putString("card_uri", card.url); cardData.putString("cards_platform", MicroBlogAPIFactory.CARDS_PLATFORM_ANDROID_12); cardData.putString("response_card_name", card.name); cardData.putString("selected_choice", String.valueOf(i + 1)); AbstractTask<CardDataMap, ParcelableCardEntity, CardPollFragment> task = new AbstractTask<CardDataMap, ParcelableCardEntity, CardPollFragment>() { @Override public void afterExecute(CardPollFragment handler, ParcelableCardEntity result) { handler.displayAndReloadPoll(result, status); } @Override public ParcelableCardEntity doLongOperation(CardDataMap cardDataMap) { final Context context = getContext(); if (context == null) return null; final TwitterCaps caps = MicroBlogAPIFactory.getInstance(context, card.account_key, true, true, TwitterCaps.class); if (caps == null) return null; try { final CardEntity cardEntity = caps.sendPassThrough(cardDataMap).getCard(); return ParcelableCardEntityUtils.fromCardEntity(cardEntity, card.account_key); } catch (MicroBlogException e) { Log.w(LOGTAG, e); } return null; } }; task.setResultHandler(CardPollFragment.this); task.setParams(cardData); TaskStarter.execute(task); } } } }; final int color = ContextCompat.getColor(context, R.color.material_light_blue_a200); final float radius = getResources().getDimension(R.dimen.element_spacing_small); for (int i = 0; i < choicesCount; i++) { final View pollItem = mPollContainer.getChildAt(i); final TextView choicePercentView = (TextView) pollItem.findViewById(R.id.choice_percent); final TextView choiceLabelView = (TextView) pollItem.findViewById(R.id.choice_label); final RadioButton choiceRadioButton = (RadioButton) pollItem.findViewById(R.id.choice_button); final int choiceIndex = i + 1; final String label = ParcelableCardEntityUtils.getAsString(card, "choice" + choiceIndex + "_label", null); final int value = ParcelableCardEntityUtils.getAsInteger(card, "choice" + choiceIndex + "_count", 0); if (label == null) throw new NullPointerException(); final float choicePercent = votesSum == 0 ? 0 : value / (float) votesSum; choiceLabelView.setText(label); choicePercentView.setText(String.format(Locale.US, "%d%%", Math.round(choicePercent * 100))); pollItem.setOnClickListener(clickListener); final boolean isSelected = selectedChoice == choiceIndex; if (showResult) { choicePercentView.setVisibility(View.VISIBLE); choiceRadioButton.setVisibility(hasChoice && isSelected ? View.VISIBLE : View.INVISIBLE); ViewSupport.setBackground(choiceLabelView, new PercentDrawable(choicePercent, radius, color)); } else { choicePercentView.setVisibility(View.GONE); choiceRadioButton.setVisibility(View.VISIBLE); ViewSupport.setBackground(choiceLabelView, null); } choiceRadioButton.setChecked(isSelected); pollItem.setClickable(selectedChoice == -1); } final String nVotes = getResources().getQuantityString(R.plurals.N_votes, votesSum, votesSum); final CharSequence timeLeft = DateUtils.getRelativeTimeSpanString(context, endDatetimeUtc.getTime(), true); mPollSummary.setText(getString(R.string.poll_summary_format, nVotes, timeLeft)); }
From source file:org.mashupmedia.editor.LibraryEditor.java
@Override public void setAsText(String idValue) throws IllegalArgumentException { long libraryId = NumberUtils.toLong(idValue); if (libraryId == 0) { return;//w ww . j av a 2 s . c om } Library library = libraryManager.getLibrary(libraryId); setValue(library); }