List of usage examples for java.lang Number intValue
public abstract int intValue();
From source file:IntRange.java
/** * <p>Constructs a new <code>IntRange</code> with the specified * minimum and maximum numbers (both inclusive).</p> * /*from w w w .j av a 2 s . c o m*/ * <p>The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.</p> * * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is <code>null</code> */ public IntRange(Number number1, Number number2) { super(); if (number1 == null || number2 == null) { throw new IllegalArgumentException("The numbers must not be null"); } int number1val = number1.intValue(); int number2val = number2.intValue(); if (number2val < number1val) { this.min = number2val; this.max = number1val; if (number2 instanceof Integer) { this.minObject = (Integer) number2; } if (number1 instanceof Integer) { this.maxObject = (Integer) number1; } } else { this.min = number1val; this.max = number2val; if (number1 instanceof Integer) { this.minObject = (Integer) number1; } if (number2 instanceof Integer) { this.maxObject = (Integer) number2; } } }
From source file:net.paoding.rose.jade.statement.UpdateQuerier.java
private Object executeSingle(StatementRuntime runtime, Class<?> returnType) { Number result; DataAccess dataAccess = dataAccessProvider.getDataAccess(// runtime.getMetaData(), runtime.getProperties()); if (returnGeneratedKeys) { ArrayList<Number> keys = new ArrayList<Number>(1); KeyHolder generatedKeyHolder = new GeneratedKeyHolder(keys); dataAccess.update(runtime.getSQL(), runtime.getArgs(), generatedKeyHolder); if (keys.size() > 0) { result = generatedKeyHolder.getKey(); } else {/*from w w w . j a va 2 s.c om*/ result = null; } } else { result = new Integer(dataAccess.update(runtime.getSQL(), runtime.getArgs(), null)); } // if (result == null || returnType == void.class) { return null; } if (returnType == result.getClass()) { return result; } // ? if (returnType == Integer.class) { return result.intValue(); } else if (returnType == Long.class) { return result.longValue(); } else if (returnType == Boolean.class) { return result.intValue() > 0 ? Boolean.TRUE : Boolean.FALSE; } else if (returnType == Double.class) { return result.doubleValue(); } else if (returnType == Float.class) { return result.floatValue(); } else if (Number.class.isAssignableFrom(returnType)) { return result; } else { throw new DataRetrievalFailureException("The generated key is not of a supported numeric type. " + "Unable to cast [" + result.getClass().getName() + "] to [" + Number.class.getName() + "]"); } }
From source file:com.btisystems.pronx.ems.AbstractMibCompiler.java
/** * Generate get accessor./*from www . j av a 2s. c o m*/ * * @param child the child * @param definedClass the defined class * @param type the type * @param field the field */ protected final void generateGetAccessor(final MibValueSymbol child, final JDefinedClass definedClass, final JType type, final String field) { final JMethod getMethod = definedClass.method(JMod.PUBLIC, type, getGetterName(field)); if (child != null) { final MibValue defaultValue = getFieldDefaultValue(child); if (defaultValue != null) { JExpression defaultReturnExpression = null; if (type == codeModel.INT || type == codeModel.LONG) { final Number javaNumber = (Number) defaultValue.toObject(); if (type == codeModel.INT) { defaultReturnExpression = JExpr.lit(javaNumber.intValue()); } else if (type == codeModel.LONG) { defaultReturnExpression = JExpr.lit(javaNumber.longValue()); } } else if (type == codeModel.ref(String.class) && defaultValue instanceof StringValue) { defaultReturnExpression = JExpr.lit(defaultValue.toString()); } if (defaultReturnExpression != null) { getMethod.body()._if(JExpr.refthis(field).eq(JExpr._null()))._then() ._return(defaultReturnExpression); generateIsDefinedAccessor(definedClass, field); } } else { generateDummyIsDefinedIfNecessary(definedClass, field); } } getMethod.body()._return(JExpr.refthis(field)); }
From source file:org.openregistry.core.service.DefaultPersonService.java
/** * This does not explicitly delete the names because its assumed the recalculation will clean it up. *///from w ww . j a v a 2 s . com public boolean deleteSystemOfRecordPerson(final SorPerson sorPerson, final boolean mistake, final String terminationTypes) { Assert.notNull(sorPerson, "sorPerson cannot be null."); final String terminationTypeToUse = terminationTypes != null ? terminationTypes : Type.TerminationTypes.UNSPECIFIED.name(); final Person person = this.personRepository.findByInternalId(sorPerson.getPersonId()); Assert.notNull(person, "person cannot be null."); if (mistake) { Set<Role> rolesToDelete = new HashSet<Role>(); for (final SorRole sorRole : sorPerson.getRoles()) { for (final Role role : person.getRoles()) { if (sorRole.getId().equals(role.getSorRoleId())) { rolesToDelete.add(role); } } } for (final Role role : rolesToDelete) { //let sorRoleElector delete the role and add another role if required sorRoleElector.removeCalculatedRole(person, role, this.personRepository.getSoRRecordsForPerson(person)); } final Number number = this.personRepository.getCountOfSoRRecordsForPerson(person); if (number.intValue() == 1) { this.personRepository.deletePerson(person); } this.personRepository.deleteSorPerson(sorPerson); return true; } //we do this explicitly here because once they're gone we can't re-calculate? We might move to this to the recalculateCalculatedPerson method. final Type terminationReason = this.referenceRepository.findType(Type.DataTypes.TERMINATION, terminationTypeToUse); for (final SorRole sorRole : sorPerson.getRoles()) { for (final Role role : person.getRoles()) { if (!role.isTerminated() && sorRole.getId().equals(role.getSorRoleId())) { role.expireNow(terminationReason, true); } } } this.personRepository.deleteSorPerson(sorPerson); this.personRepository.savePerson(person); Person p = recalculatePersonBiodemInfo(person, sorPerson, RecalculationType.DELETE, mistake); this.personRepository.savePerson(p); return true; }
From source file:com.sinosoft.one.data.jade.statement.UpdateQuerier.java
private Object executeSingle(StatementRuntime runtime, Class<?> returnType) { // DAOIdentity?1/20 if (returnType == Identity.class) { if (new Random().nextInt(20) == 1) { new IllegalArgumentException( "message by zhiliang.wang: change the deprecated Identity to @ReturnGeneratedKeys please: " + runtime.getMetaData()).printStackTrace(); }//from w w w.j a va 2s . c om } Number result; DataAccess dataAccess = new DataAccessImpl(em); if (returnGeneratedKeys) { //ArrayList<Number> keys = new ArrayList<Number>(1); List<Map<String, Object>> keys = new ArrayList<Map<String, Object>>(); KeyHolder generatedKeyHolder = new GeneratedKeyHolder(keys); dataAccess.update(runtime.getSQL(), runtime.getArgs(), generatedKeyHolder); if (keys.size() > 0) { result = generatedKeyHolder.getKey(); } else { result = null; } } else { result = new Integer(dataAccess.update(runtime.getSQL(), runtime.getArgs(), null)); } // if (result == null || returnType == void.class) { return null; } if (returnType == result.getClass()) { return result; } // ? if (returnType == Integer.class) { return result.intValue(); } else if (returnType == Long.class) { return result.longValue(); } else if (returnType == Boolean.class) { return result.intValue() > 0 ? Boolean.TRUE : Boolean.FALSE; } else if (returnType == Double.class) { return result.doubleValue(); } else if (returnType == Float.class) { return result.floatValue(); } else if (returnType == Identity.class) { return new Identity((Number) result); } else if (Number.class.isAssignableFrom(returnType)) { return result; } else { throw new DataRetrievalFailureException("The generated key is not of a supported numeric type. " + "Unable to cast [" + result.getClass().getName() + "] to [" + Number.class.getName() + "]"); } }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
public <C extends Containerable> int countContainersAttempt(Class<C> type, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, OperationResult result) { boolean cases = AccessCertificationCaseType.class.equals(type); boolean workItems = AccessCertificationWorkItemType.class.equals(type); boolean caseWorkItems = CaseWorkItemType.class.equals(type); if (!cases && !workItems && !caseWorkItems) { throw new UnsupportedOperationException( "Only AccessCertificationCaseType or AccessCertificationWorkItemType or CaseWorkItemType is supported here now."); }//from w w w.j a v a 2s .co m LOGGER_PERFORMANCE.debug("> count containers {}", type.getSimpleName()); Session session = null; try { session = baseHelper.beginReadOnlyTransaction(); QueryEngine2 engine = new QueryEngine2(getConfiguration(), extItemDictionary, prismContext); RQuery rQuery = engine.interpret(query, type, options, true, session); Number longCount = (Number) rQuery.uniqueResult(); LOGGER.trace("Found {} objects.", longCount); session.getTransaction().commit(); return longCount != null ? longCount.intValue() : 0; } catch (QueryException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); throw new AssertionError("Shouldn't get here; previous method call should throw an exception."); } finally { baseHelper.cleanupSessionAndResult(session, result); } }
From source file:com.prowidesoftware.swift.model.field.Field61.java
/** * Set the component5 from a Number object. * <br />/*from w ww . j av a2s.c om*/ * <em>If the component being set is a fixed length number, the argument will not be * padded.</em> It is recommended for these cases to use the setComponent5(String) * method. * * @see #setComponent5(String) * * @param component5 the Number with the component5 content to set */ public Field61 setComponent5(java.lang.Number component5) { if (component5 != null) { setComponent(5, "" + component5.intValue()); } return this; }
From source file:com.rockhoppertech.symchords.fx.SymChordsController.java
@FXML void initialize() { assert IntervalsTextField != null : "fx:id=\"IntervalsTextField\" was not injected: check your FXML file 'symchords.fxml'."; assert baseOctaveCombo != null : "fx:id=\"baseOctaveCombo\" was not injected: check your FXML file 'symchords.fxml'."; assert basePitchCombo != null : "fx:id=\"basePitchCombo\" was not injected: check your FXML file 'symchords.fxml'."; assert octavesSlider != null : "fx:id=\"octavesSlider\" was not injected: check your FXML file 'symchords.fxml'."; assert patternTextField != null : "fx:id=\"patternTextField\" was not injected: check your FXML file 'symchords.fxml'."; assert relationshipGroup != null : "fx:id=\"relationshipGroup\" was not injected: check your FXML file 'symchords.fxml'."; assert relativeRadio != null : "fx:id=\"relativeRadio\" was not injected: check your FXML file 'symchords.fxml'."; assert unitSlider != null : "fx:id=\"unitSlider\" was not injected: check your FXML file 'symchords.fxml'."; grandStaff.setFontSize(24d);// ww w . j a va 2 s . c o m grandStaff.drawShapes(); patternStaff.setFontSize(24d); patternStaff.drawShapes(); baseOctaveCombo.getSelectionModel().select(5); basePitchCombo.getSelectionModel().select(0); pitchProperty.bindBidirectional(pitchSlider.valueProperty()); // sliderText.setText(Math.round(pitchSlider.getValue()) + ""); PitchFormat.getInstance().setWidth(4); sliderText.setText(PitchFormat.getInstance().format((int) pitchSlider.getValue())); pitchSlider.valueProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) { if (newValue == null) { sliderText.setText(""); return; } basePitchCombo.setValue(PitchFormat.getPitchString(newValue.intValue())); baseOctaveCombo.setValue("" + newValue.intValue() / 12); sliderText.setText(PitchFormat.getInstance().format(newValue.intValue())); // sliderText.setText(Math.round(newValue.intValue()) + ""); } }); basePitchCombo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) { int pitch = PitchFactory.getPitch(newValue + "0").getMidiNumber(); int oct = Integer.parseInt(baseOctaveCombo.getSelectionModel().getSelectedItem()); pitchProperty.set(pitch + (oct * 12)); } }); baseOctaveCombo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) { int oct = Integer.parseInt(newValue); int pitch = PitchFactory.getPitch(basePitchCombo.getSelectionModel().getSelectedItem() + "0") .getMidiNumber(); pitchProperty.set(pitch + (oct * 12)); } }); // java 8 // basePitchCombo.getSelectionModel().selectedItemProperty().addListener( // (ObservableValue<? extends String> ov, String oldValue, String // newValue) -> { // int pitch = Integer.parseInt(newValue); // int oct = // Integer.parseInt(baseOctaveCombo.getSelectionModel().getSelectedItem()); // pitchProperty.set(pitch + oct); // }); // baseOctaveCombo.getSelectionModel().selectedItemProperty().addListener( // (ObservableValue<? extends String> ov, String oldValue, String // newValue) -> { // int oct = Integer.parseInt(newValue); // int pitch = // Integer.parseInt(basePitchCombo.getSelectionModel().getSelectedItem()); // pitchProperty.set(pitch + oct); // }); model = new SymModel(); model.absoluteProperty().bind(this.absoluteRadio.selectedProperty()); // model.relativeProperty().bind(this.relativeRadio.selectedProperty()); model.basePitchProperty().bind(this.pitchProperty); model.nOctavesProperty().bind(this.octavesSlider.valueProperty()); model.unitProperty().bind(this.unitSlider.valueProperty()); // set up initial value ObservableList<Integer> ol = FXCollections.observableArrayList(); ol.add(1); setIntervals(ol); // now handle input. turn the string into an array. this.IntervalsTextField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> arg0, String oldValue, String newValue) { String[] a = newValue.split("\\s+"); ObservableList<Integer> ol = FXCollections.observableArrayList(); for (final String ss : a) { ol.add(Integer.parseInt(ss)); } setIntervals(ol); } }); model.intervalsProperty().bind(this.intervalsProperty); this.resetPattern(); this.patternTextField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> arg0, String oldValue, String newValue) { logger.debug("new value '{}'", newValue); newValue = newValue.replaceAll("\\{", ""); newValue = newValue.replaceAll("\\}", ""); newValue = newValue.replaceAll(",", " "); logger.debug("new value '{}'", newValue); String[] a = newValue.split("\\s+"); ObservableList<Integer> ol = FXCollections.observableArrayList(); for (final String ss : a) { ol.add(Integer.parseInt(ss)); } // setIntervals(ol); } }); patternListView.setCellFactory(new Callback<ListView<int[]>, ListCell<int[]>>() { @Override public ListCell<int[]> call(ListView<int[]> list) { return new PatternListCell(); } }); updatePatternList(); patternListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<int[]>() { @Override public void changed(ObservableValue<? extends int[]> observable, int[] oldValue, int[] newValue) { pattern = newValue; patternCalculate(); patternTextField.setText(ArrayUtils.toString(pattern)); } }); setupDragonDrop(); trackList.setCellFactory(new Callback<ListView<MIDITrack>, ListCell<MIDITrack>>() { @Override public ListCell<MIDITrack> call(ListView<MIDITrack> list) { return new TrackListCell(); } }); trackList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<MIDITrack>() { @Override public void changed(ObservableValue<? extends MIDITrack> observable, MIDITrack oldValue, MIDITrack newValue) { model.setMIDITrack(newValue); // SymParams params = model.getParamsForTrack(newValue); SymParams params = (SymParams) newValue.getUserData(); logger.debug("params {}", params); if (params != null) { int pitch = params.getBasePitch() % 12; String ps = PitchFormat.getPitchString(pitch); basePitchCombo.setValue(ps); String oct = "" + params.getBasePitch() / 12; baseOctaveCombo.setValue(oct); String intervals = ListUtils.asIntString(params.getIntervals()); IntervalsTextField.setText(intervals); octavesSlider.setValue(params.getnOctaves()); unitSlider.setValue(params.getUnit()); relativeRadio.setSelected(params.isRelative()); absoluteRadio.setSelected(!params.isRelative()); } } }); model.midiTrackProperty().addListener(new ChangeListener<MIDITrack>() { @Override public void changed(ObservableValue<? extends MIDITrack> arg0, MIDITrack arg1, MIDITrack newTrack) { if (durationModifierCB.isSelected()) { modifierValuesTextField.setText(MIDITrack.getDurationsAsString(newTrack)); } if (pitchModifierCB.isSelected()) { modifierValuesTextField.setText(MIDITrack.getPitchesMIDINumbersAsString(newTrack)); } if (startBeatModifierCB.isSelected()) { modifierValuesTextField.setText(MIDITrack.getStartBeatsAsString(newTrack)); } logger.debug("midi track property changed {}", newTrack); grandStaff.setTrack(newTrack); grandStaff.drawShapes(); } }); }
From source file:cc.aileron.dao.db.G2DaoImpl.java
@Override public <C> G2DaoWhere<T> where(final C condition, final Class<C> wtype) { return new G2DaoWhere<T>() { @Override//from w w w.j a v a 2 s .c o m public int delete() { final Number result = G2DaoImpl.this.execute(DELETE, null, condition, wtype); return result != null ? result.intValue() : 0; } @Override public void execute() { G2DaoImpl.this.execute(EXECUTE, null, condition, wtype); } @Override public G2DaoFinder<T> find() { final PojoAccessorManager manager = G2DaoImpl.this.manager; final Provider<PojoAccessor<T>> provider = G2DaoImpl.this.provider; return new G2DaoFinder<T>() { @Override public void bind(final T object) { if (object == null) { throw new IllegalArgumentException("bindable object is null"); } final PojoAccessor<T> accessor = manager.from(object); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); if (!resultSet.next()) { return; } bind(accessor, columnNames, resultSet); } }); } @Override public int count() { final ObjectContainer<Integer> c = new ObjectContainer<Integer>(0); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException { if (resultSet.next()) { c.value = resultSet.getInt(1); } } @Override public G2DaoMethod method() { return G2DaoMethod.COUNT; } }); return c.value; } @Override public void each(final Procedure<T> procedure) { find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); while (resultSet.next()) { final PojoAccessor<T> accessor = provider.get(); bind(accessor, columnNames, resultSet); final T target = accessor.toTarget(); procedure.call(target); } } @Override public boolean isEach() { return true; } }); } @Override public void each(final Procedure<T> procedure, final G2DaoPaging paging) { find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); final int offset = paging.offset(); final int size = paging.limit(); int i = 0; boolean isNext = offset == 0 ? resultSet.next() : resultSet.absolute(offset); while (isNext) { i += 1; if (size < i) { resultSet.close(); break; } final PojoAccessor<T> accessor = provider.get(); bind(accessor, columnNames, resultSet); final T target = accessor.toTarget(); procedure.call(target); isNext = resultSet.next(); } } }); } @Override public boolean exist() { final ObjectContainer<Boolean> c = new ObjectContainer<Boolean>(false); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException { c.value = resultSet.next(); } }); return c.value; } @Override public List<T> list() { final ObjectContainer<List<T>> c = new ObjectContainer<List<T>>(new ArrayList<T>(50)); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); while (resultSet.next()) { final PojoAccessor<T> accessor = provider.get(); bind(accessor, columnNames, resultSet); c.value.add(accessor.toTarget()); } } }); return c.value; } @Override public List<T> list(final G2DaoPaging paging) { final ObjectContainer<List<T>> c = new ObjectContainer<List<T>>(new ArrayList<T>(50)); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); final int offset = paging.offset(); final int size = paging.limit(); int i = 0; boolean isNext = offset == 0 ? resultSet.next() : resultSet.absolute(offset); while (isNext) { i += 1; if (size < i) { resultSet.close(); break; } final PojoAccessor<T> accessor = provider.get(); bind(accessor, columnNames, resultSet); c.value.add(accessor.toTarget()); isNext = resultSet.next(); } } }); return c.value; } @Override public T one() { final String key; if (isCacheable) { final StringBuilder buff = new StringBuilder(); for (final Method method : (wtype != null ? wtype : condition.getClass().getInterfaces()[0]).getDeclaredMethods()) { try { final Object v = method.invoke(condition); buff.append(v).append('\0'); } catch (final IllegalArgumentException e) { throw new Error(e); } catch (final IllegalAccessException e) { throw new Error(e); } catch (final InvocationTargetException e) { throw new Error(e); } } key = buff.toString(); final T val = Cast.<T>cast(cache.get(key)); if (val != null) { return val; } } else { key = null; } final ObjectContainer<T> c = new ObjectContainer<T>(); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final PojoAccessor<T> accessor = provider.get(); final List<String> columnNames = getColumnNames(resultSet); if (!resultSet.next()) { return; } bind(accessor, columnNames, resultSet); c.value = accessor.toTarget(); } }); if (isCacheable) { cache.put(key, c.value); } return c.value; } }; } @Override public <R> G2DaoFinder<R> find(final Factory<R, ? super T> factory) { final PojoAccessorManager manager = G2DaoImpl.this.manager; final Provider<PojoAccessor<R>> provider = new Provider<PojoAccessor<R>>() { @Override public PojoAccessor<R> get() { return manager.from(factory.get(G2DaoImpl.this.provider.get().toTarget())); } }; return new G2DaoFinder<R>() { @Override public void bind(final R object) { if (object == null) { throw new IllegalArgumentException("bindable object is null"); } final PojoAccessor<R> accessor = manager.from(object); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); if (!resultSet.next()) { return; } bind(accessor, columnNames, resultSet); } }); } @Override public int count() { final ObjectContainer<Integer> c = new ObjectContainer<Integer>(0); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException { if (resultSet.next()) { c.value = resultSet.getInt(1); } } @Override public G2DaoMethod method() { return G2DaoMethod.COUNT; } }); return c.value; } @Override public void each(final Procedure<R> procedure) { find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); while (resultSet.next()) { final PojoAccessor<R> accessor = provider.get(); bind(accessor, columnNames, resultSet); final R target = accessor.toTarget(); procedure.call(target); } } }); } @Override public void each(final Procedure<R> procedure, final G2DaoPaging paging) { find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); final int offset = paging.offset(); final int size = paging.limit(); int i = 0; boolean isNext = offset == 0 ? resultSet.next() : resultSet.absolute(offset); while (isNext) { i += 1; if (size < i) { resultSet.close(); break; } final PojoAccessor<R> accessor = provider.get(); bind(accessor, columnNames, resultSet); final R target = accessor.toTarget(); procedure.call(target); isNext = resultSet.next(); } } }); } @Override public boolean exist() { final ObjectContainer<Boolean> c = new ObjectContainer<Boolean>(false); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException { c.value = resultSet.next(); } }); return c.value; } @Override public List<R> list() { final ObjectContainer<List<R>> c = new ObjectContainer<List<R>>(new ArrayList<R>(50)); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); while (resultSet.next()) { final PojoAccessor<R> accessor = provider.get(); bind(accessor, columnNames, resultSet); c.value.add(accessor.toTarget()); } } }); return c.value; } @Override public List<R> list(final G2DaoPaging paging) { final ObjectContainer<List<R>> c = new ObjectContainer<List<R>>(new ArrayList<R>(50)); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final List<String> columnNames = getColumnNames(resultSet); final int offset = paging.offset(); final int size = paging.limit(); int i = 0; boolean isNext = offset == 0 ? resultSet.next() : resultSet.absolute(offset); while (isNext) { i += 1; if (size < i) { resultSet.close(); break; } final PojoAccessor<R> accessor = provider.get(); bind(accessor, columnNames, resultSet); c.value.add(accessor.toTarget()); isNext = resultSet.next(); } } }); return c.value; } @Override public R one() { final String key; if (isCacheable) { final StringBuilder buff = new StringBuilder(); for (final Method method : (wtype != null ? wtype : condition.getClass().getInterfaces()[0]).getDeclaredMethods()) { try { buff.append(method.invoke(condition).toString()).append('\0'); } catch (final IllegalArgumentException e) { throw new Error(e); } catch (final IllegalAccessException e) { throw new Error(e); } catch (final InvocationTargetException e) { throw new Error(e); } } key = buff.toString(); final R val = Cast.<R>cast(cache.get(key)); if (val != null) { return val; } } else { key = null; } final ObjectContainer<R> c = new ObjectContainer<R>(); find(wtype, condition, new G2DaoResultHandler() { @Override public void execute(final ResultSet resultSet) throws SQLException, PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException { final PojoAccessor<R> accessor = provider.get(); final List<String> columnNames = getColumnNames(resultSet); if (!resultSet.next()) { return; } bind(accessor, columnNames, resultSet); c.value = accessor.toTarget(); } }); if (isCacheable) { cache.put(key, c.value); } return c.value; } }; } @Override public long insert(final T value) { final Number result = G2DaoImpl.this.execute(INSERT, value, condition, wtype); return result != null ? result.longValue() : 0; } @Override public int update(final T value) { final Number result = G2DaoImpl.this.execute(UPDATE, value, condition, wtype); return result != null ? result.intValue() : 0; } /** * @param invoker * @param condition */ void find(final Class<?> wtype, final Object condition, final G2DaoResultHandler invoker) { if (condition == null) { return; } final Connection connection = transactionManager.get(); try { executor.execute(transactionManager.db(), connection, wtype, condition, invoker); } catch (final Throwable e) { throw new Error("G2Dao [" + type.getName() + "] find by " + (condition == G2DaoNoCondition.NO_CONDITION ? "all" : sqlName.get(condition, wtype)), e); } finally { transactionManager.close(connection); } } }; }
From source file:com.gzj.tulip.jade.statement.UpdateQuerier.java
private Object executeSingle(StatementRuntime runtime) { Number result; DataAccess dataAccess = dataAccessFactory.getDataAccess(// runtime.getMetaData(), runtime.getAttributes()); if (returnGeneratedKeys.shouldReturnGerneratedKeys(runtime)) { ArrayList<Map<String, Object>> keys = new ArrayList<Map<String, Object>>(1); KeyHolder generatedKeyHolder = new GeneratedKeyHolder(keys); dataAccess.update(runtime.getSQL(), runtime.getArgs(), generatedKeyHolder); if (keys.size() > 0) { result = generatedKeyHolder.getKey(); } else {/*from w ww . j ava 2 s.c o m*/ result = null; } } else { result = new Integer(dataAccess.update(runtime.getSQL(), runtime.getArgs(), null)); } // if (result == null || returnType == void.class) { return null; } if (returnType == result.getClass()) { return result; } // ? if (returnType == Integer.class) { return result.intValue(); } else if (returnType == Long.class) { return result.longValue(); } else if (returnType == Boolean.class) { return result.intValue() > 0 ? Boolean.TRUE : Boolean.FALSE; } else if (returnType == Double.class) { return result.doubleValue(); } else if (returnType == Float.class) { return result.floatValue(); } else if (returnType == Number.class) { return result; } else if (returnType == String.class || returnType == CharSequence.class) { return String.valueOf(result); } else { throw new DataRetrievalFailureException( "The generated key is not of a supported numeric type: " + returnType.getName()); } }