List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:cl.gisred.android.MicroMedidaActivity.java
private void cerrarFormCrear(boolean bSave, View v) { if (bSave) {//from ww w . j ava2s .c om final AtomicReference<String> resp = new AtomicReference<>(""); if (!validarForm(v)) { DialogoConfirmacion oDialog = new DialogoConfirmacion(); oDialog.show(getFragmentManager(), "tagAlert"); return; } else { View vAction = getLayoutValidate(v); Map<String, Object> objectMap = new HashMap<>(); for (View view : vAction.getTouchables()) { if (view.getClass().equals(GisEditText.class)) { GisEditText oText = (GisEditText) view; if (oText.getText() != null && !oText.getText().toString().isEmpty()) { if (oText.getId() == R.id.txtPoste) { objectMap.put("id_poste_camara", oText.getIdObjeto()); objectMap.put("tipo_nodo_conex", oText.getTipo()); } else if (oText.getId() == R.id.txtTramoBt) { objectMap.put("id_tramo_bt", oText.getText().toString()); } else if (oText.getId() == R.id.txtAddress) { objectMap.put("id_direccion", oText.getIdObjeto()); objectMap.put("tipo_direccion", oText.getTipo()); } } } else if (view.getClass().getGenericSuperclass().equals(EditText.class)) { EditText oText = (EditText) view; if (oText.getId() == R.id.txtNroMedidor) { String oVal = (oText.getText().toString().isEmpty()) ? "0" : oText.getText().toString(); objectMap.put("nro_medidor", oVal); } } else if (view.getClass().getGenericSuperclass().equals(Spinner.class)) { Spinner oSpinner = (Spinner) view; String sValue = oSpinner.getSelectedItem().toString(); if (oSpinner.getId() == R.id.spinnerMarcaMed) objectMap.put("marca_medidor", sValue); else if (oSpinner.getId() == R.id.spinnerFaseCon) objectMap.put("fase_conex", sValue); else if (oSpinner.getId() == R.id.spinnerObservacion) objectMap.put("observacion", sValue); } } objectMap.put("empresa", empresa); objectMap.put("modulo", modulo); if (mLocation != null) { Point p = (Point) GeometryEngine.project(mLocation, egs, wm); objectMap.put("X", p.getX()); objectMap.put("Y", p.getY()); } Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap); Graphic[] adds = { newFeatureGraphic }; LyAddMicroMed.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() { @Override public void onCallback(FeatureEditResult[][] featureEditResults) { if (featureEditResults[0] != null) { if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) { resp.set("Guardado Correctamente Id: " + featureEditResults[0][0].getObjectId()); runOnUiThread(new Runnable() { @Override public void run() { Util.showConfirmation(MicroMedidaActivity.this, resp.get()); } }); } } } @Override public void onError(Throwable throwable) { resp.set("Error al ingresar: " + throwable.getLocalizedMessage()); Log.w("onError", resp.get()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MicroMedidaActivity.this, resp.get(), Toast.LENGTH_SHORT).show(); } }); } }); } } bMapTap = false; oUbicacion = null; if (mBusquedaLayer != null && myMapView.getLayerByID(mBusquedaLayer.getID()) != null) myMapView.removeLayer(mBusquedaLayer); if (mUbicacionLayer != null && myMapView.getLayerByID(mUbicacionLayer.getID()) != null) myMapView.removeLayer(mUbicacionLayer); if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null) myMapView.removeLayer(mSeleccionLayer); if (bVerCapas) toogleCapas(fabVerCapas); if (bIngCliente) menuMultipleActions.setVisibility(View.VISIBLE); menuMicroActions.setVisibility(View.VISIBLE); fabShowForm.setVisibility(View.GONE); formCrear.dismiss(); if (LyAddMicroMed != null) LyAddMicroMed.setVisible(true); }
From source file:com.jivesoftware.os.upena.deployable.UpenaMain.java
public AmzaService startAmza(String workingDir, AmzaStats amzaStats, BAInterner baInterner, int writerId, RingHost ringHost, RingMember ringMember, OAuthSigner authSigner, TenantAwareHttpClient<String> systemTakeClient, TenantAwareHttpClient<String> stripedTakeClient, TenantAwareHttpClient<String> ringClient, AtomicReference<Callable<RingTopology>> topologyProvider, String clusterDiscoveryName, String multicastGroup, int multicastPort) throws Exception { //Deployable deployable = new Deployable(new String[0]); SnowflakeIdPacker idPacker = new SnowflakeIdPacker(); JiveEpochTimestampProvider timestampProvider = new JiveEpochTimestampProvider(); SickThreads sickThreads = new SickThreads(); SickPartitions sickPartitions = new SickPartitions(); //deployable.addHealthCheck(new SickThreadsHealthCheck(deployable.config(AmzaSickThreadsHealthConfig.class), sickThreads)); //deployable.addHealthCheck(new SickPartitionsHealthCheck(sickPartitions)); TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(new ConstantWriterIdProvider(writerId), idPacker, timestampProvider); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.INDENT_OUTPUT, false); PartitionPropertyMarshaller partitionPropertyMarshaller = new PartitionPropertyMarshaller() { @Override// ww w. j a va2 s . c om public PartitionProperties fromBytes(byte[] bytes) { try { return mapper.readValue(bytes, PartitionProperties.class); } catch (IOException e) { throw new RuntimeException(e); } } @Override public byte[] toBytes(PartitionProperties partitionProperties) { try { return mapper.writeValueAsBytes(partitionProperties); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }; BinaryPrimaryRowMarshaller primaryRowMarshaller = new BinaryPrimaryRowMarshaller(); // hehe you cant change this :) BinaryHighwaterRowMarshaller highwaterRowMarshaller = new BinaryHighwaterRowMarshaller(baInterner); RowsTakerFactory systemRowsTakerFactory = () -> new HttpRowsTaker(amzaStats, systemTakeClient, mapper, baInterner); RowsTakerFactory rowsTakerFactory = () -> new HttpRowsTaker(amzaStats, stripedTakeClient, mapper, baInterner); AvailableRowsTaker availableRowsTaker = new HttpAvailableRowsTaker(ringClient, baInterner, mapper); AquariumStats aquariumStats = new AquariumStats(); QuorumTimeouts quorumTimeoutsConfig = bindDefault(QuorumTimeouts.class); HealthTimer quorumLatency = HealthFactory.getHealthTimer(QuorumLatency.class, TimerHealthChecker.FACTORY); TriggerTimeoutHealthCheck quorumTimeoutHealthCheck = new TriggerTimeoutHealthCheck( () -> amzaStats.getGrandTotal().quorumTimeouts.longValue(), quorumTimeoutsConfig); //deployable.addHealthCheck(quorumTimeoutHealthCheck); //LABPointerIndexConfig amzaLabConfig = deployable.config(LABPointerIndexConfig.class); LABPointerIndexConfig amzaLabConfig = bindDefault(UpenaLABPointerIndexConfig.class); AmzaServiceConfig amzaServiceConfig = new AmzaServiceConfig(); amzaServiceConfig.systemRingSize = 1; amzaServiceConfig.workingDirectories = new String[] { new File(workingDir, "state").getAbsolutePath() }; amzaServiceConfig.aquariumLivelinessFeedEveryMillis = 5_000; amzaServiceConfig.checkIfCompactionIsNeededIntervalInMillis = 30_000; amzaServiceConfig.deltaMergeThreads = 2; amzaServiceConfig.maxUpdatesBeforeDeltaStripeCompaction = 10_000; amzaServiceConfig.numberOfTakerThreads = 2; amzaServiceConfig.hardFsync = true; amzaServiceConfig.takeSlowThresholdInMillis = 1_000; amzaServiceConfig.rackDistributionEnabled = false; Set<RingMember> blacklistRingMembers = Sets.newHashSet(); AmzaService amzaService = new AmzaServiceInitializer().initialize(amzaServiceConfig, baInterner, aquariumStats, amzaStats, quorumLatency, () -> { Callable<RingTopology> ringTopologyCallable = topologyProvider.get(); if (ringTopologyCallable != null) { try { return ringTopologyCallable.call().entries.size(); } catch (Exception x) { LOG.error("issue determining system ring size", x); } } return -1; }, sickThreads, sickPartitions, primaryRowMarshaller, highwaterRowMarshaller, ringMember, ringHost, blacklistRingMembers, orderIdProvider, idPacker, partitionPropertyMarshaller, (workingIndexDirectories, indexProviderRegistry, ephemeralRowIOProvider, persistentRowIOProvider, partitionStripeFunction) -> { indexProviderRegistry .register( new BerkeleyDBWALIndexProvider(BerkeleyDBWALIndexProvider.INDEX_CLASS_NAME, partitionStripeFunction, workingIndexDirectories), persistentRowIOProvider); indexProviderRegistry.register(new LABPointerIndexWALIndexProvider(amzaLabConfig, LABPointerIndexWALIndexProvider.INDEX_CLASS_NAME, partitionStripeFunction, workingIndexDirectories), persistentRowIOProvider); }, availableRowsTaker, systemRowsTakerFactory, rowsTakerFactory, Optional.<TakeFailureListener>absent(), rowsChanged -> { }); topologyProvider.set(() -> amzaService.getRingReader().getRing(AmzaRingReader.SYSTEM_RING, -1)); amzaService.start(ringMember, ringHost); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Amza Service Started"); LOG.info("-----------------------------------------------------------------------"); if (clusterDiscoveryName != null) { AmzaDiscovery amzaDiscovery = new AmzaDiscovery(amzaService.getRingReader(), amzaService.getRingWriter(), clusterDiscoveryName, multicastGroup, multicastPort, new AtomicInteger(amzaService.getRingReader().getRingSize(AmzaRingReader.SYSTEM_RING, -1)) // Grrr ); amzaDiscovery.start(); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Amza Service Discovery Online"); LOG.info("-----------------------------------------------------------------------"); } else { LOG.info("-----------------------------------------------------------------------"); LOG.info("| Amza Service is in manual Discovery mode. No cluster discovery name was specified"); LOG.info("-----------------------------------------------------------------------"); } return amzaService; }
From source file:org.apache.hadoop.hbase.client.TestFromClientSide.java
@Ignore("Flakey: HBASE-8989") @Test/*w w w .jav a 2s . c o m*/ public void testClientPoolThreadLocal() throws IOException { final byte[] tableName = Bytes.toBytes("testClientPoolThreadLocal"); int poolSize = Integer.MAX_VALUE; int numVersions = 3; Configuration conf = TEST_UTIL.getConfiguration(); conf.set(HConstants.HBASE_CLIENT_IPC_POOL_TYPE, "thread-local"); conf.setInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, poolSize); final HTable table = TEST_UTIL.createTable(tableName, new byte[][] { FAMILY }, conf, 3); final long ts = EnvironmentEdgeManager.currentTimeMillis(); final Get get = new Get(ROW); get.addColumn(FAMILY, QUALIFIER); get.setMaxVersions(); for (int versions = 1; versions <= numVersions; versions++) { Put put = new Put(ROW); put.add(FAMILY, QUALIFIER, ts + versions, VALUE); table.put(put); Result result = table.get(get); NavigableMap<Long, byte[]> navigableMap = result.getMap().get(FAMILY).get(QUALIFIER); assertEquals("The number of versions of '" + FAMILY + ":" + QUALIFIER + " did not match " + versions + "; " + put.toString() + ", " + get.toString(), versions, navigableMap.size()); for (Map.Entry<Long, byte[]> entry : navigableMap.entrySet()) { assertTrue("The value at time " + entry.getKey() + " did not match what was put", Bytes.equals(VALUE, entry.getValue())); } } final Object waitLock = new Object(); ExecutorService executorService = Executors.newFixedThreadPool(numVersions); final AtomicReference<AssertionError> error = new AtomicReference<AssertionError>(null); for (int versions = numVersions; versions < numVersions * 2; versions++) { final int versionsCopy = versions; executorService.submit(new Callable<Void>() { @Override public Void call() { try { Put put = new Put(ROW); put.add(FAMILY, QUALIFIER, ts + versionsCopy, VALUE); table.put(put); Result result = table.get(get); NavigableMap<Long, byte[]> navigableMap = result.getMap().get(FAMILY).get(QUALIFIER); assertEquals( "The number of versions of '" + Bytes.toString(FAMILY) + ":" + Bytes.toString(QUALIFIER) + " did not match " + versionsCopy, versionsCopy, navigableMap.size()); for (Map.Entry<Long, byte[]> entry : navigableMap.entrySet()) { assertTrue("The value at time " + entry.getKey() + " did not match what was put", Bytes.equals(VALUE, entry.getValue())); } synchronized (waitLock) { waitLock.wait(); } } catch (Exception e) { } catch (AssertionError e) { // the error happens in a thread, it won't fail the test, // need to pass it to the caller for proper handling. error.set(e); LOG.error(e); } return null; } }); } synchronized (waitLock) { waitLock.notifyAll(); } executorService.shutdownNow(); assertNull(error.get()); }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
@Override public <E> TableMetadata<E> resolve(final Class<E> entityType) { log.info("Resolving metadata for " + entityType.getCanonicalName()); final String tableName; final String schema; final Set<Set<String>> uniqueColumns = new HashSet<Set<String>>(); final Set<String> keyColumns = new HashSet<String>(); final Set<String> foreignKeys = new HashSet<String>(); final HashSet<RelationMetadata<E, ?>> foreignReferences = new HashSet<RelationMetadata<E, ?>>(); if (entityType.isAnnotationPresent(Table.class)) { final Table table = entityType.getAnnotation(Table.class); tableName = table.name().isEmpty() ? entityType.getSimpleName() : table.name(); schema = table.schema();// www . ja va2 s .c o m for (UniqueConstraint constraint : table.uniqueConstraints()) { final HashSet<String> columns = new HashSet<String>(); uniqueColumns.add(columns); Collections.addAll(columns, constraint.columnNames()); } } else { tableName = entityType.getSimpleName(); schema = NO_SCHEMA; } final Set<StoredProcedureMetadata> storedProcedures = new HashSet<StoredProcedureMetadata>(); if (entityType.isAnnotationPresent(StoredProcedure.class)) { storedProcedures.add(getStoredProcedureMetadata(entityType.getAnnotation(StoredProcedure.class))); } else if (entityType.isAnnotationPresent(StoredProcedures.class)) { final StoredProcedure[] procedures = entityType.getAnnotation(StoredProcedures.class).value(); for (StoredProcedure procedure : procedures) { storedProcedures.add(getStoredProcedureMetadata(procedure)); } } //noinspection unchecked if (!withMethods(entityType).keep(new GetterMethodFilter()) .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class)) .keep(new AnnotatedElementFilter(Transient.class)).isEmpty()) { throw new TransientColumnFoundError(entityType); } final Collection<SequenceMetadata> sequences = new HashSet<SequenceMetadata>(); final HashSet<ConstraintMetadata> constraints = new HashSet<ConstraintMetadata>(); final AtomicReference<ColumnMetadata> versionColumn = new AtomicReference<ColumnMetadata>(); //noinspection unchecked final List<Method> getters = withMethods(entityType).keep(new GetterMethodFilter()).list(); final List<Method> filteredGetters = new ArrayList<Method>(); for (Method getter : getters) { final PropertyAccessorFilter filter = new PropertyAccessorFilter( ReflectionUtils.getPropertyName(getter.getName())); final Method method = with(filteredGetters).find(filter); if (method == null) { filteredGetters.add(getter); } else if (method.getDeclaringClass().equals(getter.getDeclaringClass())) { filteredGetters.remove(method); filteredGetters.add(pickGetter(method, getter)); } } getters.clear(); getters.addAll(filteredGetters); //noinspection unchecked final Collection<ColumnMetadata> tableColumns = with(getters) .drop(new AnnotatedElementFilter(Transient.class)).drop(new AnnotatedElementFilter(OneToMany.class)) .drop(new AnnotatedElementFilter(ManyToMany.class)).drop(new Filter<Method>() { @Override public boolean accepts(Method item) { return item.isAnnotationPresent(OneToOne.class) && !item.isAnnotationPresent(JoinColumn.class); } }).drop(new PropertyAccessorFilter(CLASS_PROPERTY)) .transform(new Transformer<Method, ColumnMetadata>() { @Override public ColumnMetadata map(Method method) { final JoinColumn joinColumn = method.getAnnotation(JoinColumn.class); Column column = method.getAnnotation(Column.class); if (column == null && joinColumn == null) { //let's assume it is a column anyway column = new DefaultColumn(); } final String propertyName = ReflectionUtils.getPropertyName(method.getName()); if (column != null && joinColumn != null) { throw new ColumnDefinitionError( "Property " + propertyName + " is defined as both a column and a join column"); } final Class<?> propertyType = method.getReturnType(); String name = column != null ? column.name() : joinColumn.name(); if (name.isEmpty()) { name = propertyName; } final boolean nullable = column != null ? column.nullable() : joinColumn.nullable(); final int length = column != null ? column.length() : 0; final int precision = column != null ? column.precision() : 0; final int scale = column != null ? column.scale() : 0; final ValueGenerationType generationType = determineValueGenerationType(method); final String valueGenerator = determineValueGenerator(method); final ColumnMetadata foreignColumn = joinColumn == null ? null : determineForeignReference(method); final int type = getColumnType(method, foreignColumn); final Class<?> declaringClass = ReflectionUtils.getDeclaringClass(method); if (method.isAnnotationPresent(BasicCollection.class) && !(Collection.class.isAssignableFrom(method.getReturnType()))) { throw new ColumnDefinitionError( "Collection column must return a collection value: " + tableName + "." + name); } final ResolvedColumnMetadata columnMetadata = new ResolvedColumnMetadata( new UnresolvedTableMetadata<E>(entityType), declaringClass, name, type, propertyName, propertyType, nullable, length, precision, scale, generationType, valueGenerator, foreignColumn, method.isAnnotationPresent(BasicCollection.class), isComplex(method, foreignColumn)); if (foreignColumn != null) { foreignKeys.add(name); } if (method.isAnnotationPresent(Id.class)) { keyColumns.add(name); } if (method.isAnnotationPresent(SequenceGenerator.class)) { final SequenceGenerator annotation = method.getAnnotation(SequenceGenerator.class); sequences.add(new ImmutableSequenceMetadata(annotation.name(), annotation.initialValue(), annotation.allocationSize())); } if (joinColumn != null) { final RelationType relationType = getRelationType(method); final CascadeMetadata cascadeMetadata = getCascadeMetadata(method); final boolean isLazy = determineLaziness(method); final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>( declaringClass, columnMetadata.getPropertyName(), true, null, null, null, relationType, cascadeMetadata, isLazy, null); reference.setForeignColumn(foreignColumn); foreignReferences.add(reference); } if (method.isAnnotationPresent(Version.class)) { if (versionColumn.get() != null) { throw new MultipleVersionColumnsError(entityType); } if (column != null) { if (columnMetadata.isNullable()) { throw new VersionColumnDefinitionError("Version column cannot be nullable: " + entityType.getCanonicalName() + "." + columnMetadata.getName()); } versionColumn.set(columnMetadata); } else { throw new VersionColumnDefinitionError( "Only local columns can be used for optimistic locking"); } } return columnMetadata; } }).list(); //handling one-to-many relations //noinspection unchecked withMethods(entityType).keep(new GetterMethodFilter()) .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)) .keep(new AnnotatedElementFilter(OneToMany.class)).each(new Processor<Method>() { @Override public void process(Method method) { if (!Collection.class.isAssignableFrom(method.getReturnType())) { throw new RelationDefinitionError( "One to many relations must be collections. Error in " + method); } final OneToMany annotation = method.getAnnotation(OneToMany.class); Class<?> foreignEntity = annotation.targetEntity().equals(void.class) ? ((Class) ((ParameterizedType) method.getGenericReturnType()) .getActualTypeArguments()[0]) : annotation.targetEntity(); String foreignColumnName = annotation.mappedBy(); final String propertyName = ReflectionUtils.getPropertyName(method.getName()); if (foreignColumnName.isEmpty()) { //noinspection unchecked final List<Method> list = withMethods(foreignEntity) .keep(new AnnotatedElementFilter(JoinColumn.class)) .keep(new AnnotatedElementFilter(ManyToOne.class)) .keep(new MethodReturnTypeFilter(entityType)).list(); if (list.isEmpty()) { throw new RelationDefinitionError( "No ManyToOne relations for " + entityType.getCanonicalName() + " were found on " + foreignEntity.getCanonicalName()); } if (list.size() > 1) { throw new RelationDefinitionError("Ambiguous one to many relationship on " + entityType.getCanonicalName() + "." + propertyName); } final Method foreignMethod = list.get(0); final Column column = foreignMethod.getAnnotation(Column.class); final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class); foreignColumnName = column == null ? joinColumn.name() : column.name(); if (foreignColumnName.isEmpty()) { foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName()); } } final List<OrderMetadata> ordering = getOrdering(foreignEntity, method.getAnnotation(OrderBy.class)); //noinspection unchecked final UnresolvedColumnMetadata foreignColumn = new UnresolvedColumnMetadata( foreignColumnName, new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)); final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>( ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null, getRelationType(method), getCascadeMetadata(method), determineLaziness(method), ordering); reference.setForeignColumn(foreignColumn); foreignReferences.add(reference); } }); //Handling one-to-one relations where the entity is not the owner of the relationship //noinspection unchecked withMethods(entityType).keep(new GetterMethodFilter()).keep(new AnnotatedElementFilter(OneToOne.class)) .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)).each(new Processor<Method>() { @Override public void process(Method method) { final OneToOne annotation = method.getAnnotation(OneToOne.class); Class<?> foreignEntity = annotation.targetEntity().equals(void.class) ? method.getReturnType() : annotation.targetEntity(); final String propertyName = ReflectionUtils.getPropertyName(method.getName()); final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>( ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null, getRelationType(method), getCascadeMetadata(method), determineLaziness(method), null); String foreignColumnName = annotation.mappedBy(); if (foreignColumnName.isEmpty()) { //noinspection unchecked final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter()) .keep(new MethodReturnTypeFilter(entityType)) .keep(new AnnotatedElementFilter(OneToOne.class)) .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class)).list(); if (methods.isEmpty()) { throw new EntityDefinitionError( "No OneToOne relations were found on " + foreignEntity.getCanonicalName() + " for " + entityType.getCanonicalName()); } if (methods.size() > 1) { throw new EntityDefinitionError("Ambiguous OneToOne relation on " + entityType.getCanonicalName() + "." + propertyName); } final Method foreignMethod = methods.get(0); final Column column = foreignMethod.getAnnotation(Column.class); final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class); foreignColumnName = column == null ? joinColumn.name() : column.name(); if (foreignColumnName.isEmpty()) { foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName()); } } //noinspection unchecked reference.setForeignColumn(new UnresolvedColumnMetadata(foreignColumnName, new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity))); foreignReferences.add(reference); } }); final HashSet<NamedQueryMetadata> namedQueries = new HashSet<NamedQueryMetadata>(); if (entityType.isAnnotationPresent(SequenceGenerator.class)) { final SequenceGenerator annotation = entityType.getAnnotation(SequenceGenerator.class); sequences.add(new ImmutableSequenceMetadata(annotation.name(), annotation.initialValue(), annotation.allocationSize())); } //finding orderings //noinspection unchecked final List<OrderMetadata> ordering = withMethods(entityType).keep(new AnnotatedElementFilter(Column.class)) .keep(new AnnotatedElementFilter(Order.class)).sort(new Comparator<Method>() { @Override public int compare(Method firstMethod, Method secondMethod) { final Order first = firstMethod.getAnnotation(Order.class); final Order second = secondMethod.getAnnotation(Order.class); return ((Integer) first.priority()).compareTo(second.priority()); } }).transform(new Transformer<Method, OrderMetadata>() { @Override public OrderMetadata map(Method input) { final Column column = input.getAnnotation(Column.class); String columnName = column.name().isEmpty() ? ReflectionUtils.getPropertyName(input.getName()) : column.name(); ColumnMetadata columnMetadata = with(tableColumns).find(new ColumnNameFilter(columnName)); if (columnMetadata == null) { columnMetadata = with(tableColumns).find(new ColumnPropertyFilter(columnName)); } if (columnMetadata == null) { throw new NoSuchColumnError(entityType, columnName); } return new ImmutableOrderMetadata(columnMetadata, input.getAnnotation(Order.class).value()); } }).list(); final ResolvedTableMetadata<E> tableMetadata = new ResolvedTableMetadata<E>(entityType, schema, tableName, constraints, tableColumns, namedQueries, sequences, storedProcedures, foreignReferences, versionColumn.get(), ordering); if (!keyColumns.isEmpty()) { constraints.add(new PrimaryKeyConstraintMetadata(tableMetadata, with(keyColumns).transform(new Transformer<String, ColumnMetadata>() { @Override public ColumnMetadata map(String columnName) { return getColumnMetadata(columnName, tableColumns, entityType); } }).list())); } if (entityType.isAnnotationPresent(NamedNativeQueries.class)) { final NamedNativeQuery[] queries = entityType.getAnnotation(NamedNativeQueries.class).value(); for (NamedNativeQuery query : queries) { namedQueries.add(new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata, QueryType.NATIVE)); } } else if (entityType.isAnnotationPresent(NamedNativeQuery.class)) { final NamedNativeQuery query = entityType.getAnnotation(NamedNativeQuery.class); namedQueries.add( new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata, QueryType.NATIVE)); } constraints .addAll(with(uniqueColumns).sort().transform(new Transformer<Set<String>, Set<ColumnMetadata>>() { @Override public Set<ColumnMetadata> map(Set<String> columns) { return with(columns).transform(new Transformer<String, ColumnMetadata>() { @Override public ColumnMetadata map(String columnName) { return getColumnMetadata(columnName, tableColumns, entityType); } }).set(); } }).transform(new Transformer<Set<ColumnMetadata>, UniqueConstraintMetadata>() { @Override public UniqueConstraintMetadata map(Set<ColumnMetadata> columns) { return new UniqueConstraintMetadata(tableMetadata, columns); } }).list()); constraints.addAll(with(foreignKeys).sort().transform(new Transformer<String, ColumnMetadata>() { @Override public ColumnMetadata map(String columnName) { return getColumnMetadata(columnName, tableColumns, entityType); } }).transform(new Transformer<ColumnMetadata, ForeignKeyConstraintMetadata>() { @Override public ForeignKeyConstraintMetadata map(ColumnMetadata columnMetadata) { return new ForeignKeyConstraintMetadata(tableMetadata, columnMetadata); } }).list()); //going after many-to-many relations //noinspection unchecked withMethods(entityType).drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)) .keep(new GetterMethodFilter()).forThose(new Filter<Method>() { @Override public boolean accepts(Method item) { return item.isAnnotationPresent(ManyToMany.class); } }, new Processor<Method>() { @Override public void process(Method method) { final ManyToMany annotation = method.getAnnotation(ManyToMany.class); Class<?> foreignEntity = annotation.targetEntity().equals(void.class) ? ((Class) ((ParameterizedType) method.getGenericReturnType()) .getActualTypeArguments()[0]) : annotation.targetEntity(); String foreignProperty = annotation.mappedBy(); if (foreignProperty.isEmpty()) { //noinspection unchecked final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter()) .keep(new AnnotatedElementFilter(ManyToMany.class)).list(); if (methods.isEmpty()) { throw new EntityDefinitionError( "Failed to locate corresponding many-to-many relation on " + foreignEntity.getCanonicalName()); } if (methods.size() == 1) { throw new EntityDefinitionError("Ambiguous many-to-many relationship defined"); } foreignProperty = ReflectionUtils.getPropertyName(methods.get(0).getName()); } final List<OrderMetadata> ordering = getOrdering(foreignEntity, method.getAnnotation(OrderBy.class)); //noinspection unchecked foreignReferences.add(new DefaultRelationMetadata<E, Object>( ReflectionUtils.getDeclaringClass(method), ReflectionUtils.getPropertyName(method.getName()), false, tableMetadata, null, new UnresolvedColumnMetadata(foreignProperty, new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)), RelationType.MANY_TO_MANY, getCascadeMetadata(method), determineLaziness(method), ordering)); } }); return tableMetadata; }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.LocalDataAccessLayer.java
/** * Pending local property changes is extremely limited. Only the types of * values which can be stored in {@link LocalPendingChangeFlags} are * supported (executable bit changes). Trying to set other named properties * will result in a failure. The caller should do an online operation for * other types.//from w w w . ja va2s .c o m */ public static GetOperation[] pendPropertyChange(final Workspace workspace, final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv, final LocalPendingChangesTable pc, final ChangeRequest[] changeRequests, final boolean silent, final AtomicReference<Failure[]> failures, final AtomicBoolean onlineOperationRequired, final String[] itemPropertyFilters) { Check.notNull(workspace, "workspace"); //$NON-NLS-1$ Check.notNullOrEmpty(changeRequests, "changeRequests"); //$NON-NLS-1$ final List<Failure> failureList = new ArrayList<Failure>(); final List<GetOperation> getOps = new ArrayList<GetOperation>(); final Set<WorkspaceLocalItem> duplicatesFilter = new HashSet<WorkspaceLocalItem>(); for (final ChangeRequest changeRequest : changeRequests) { if (null == changeRequest) { continue; } // We can only handle the executable or symbolic link property // offline. if (changeRequest.getProperties() != null) { for (final PropertyValue value : changeRequest.getProperties()) { if (!(PropertyConstants.EXECUTABLE_KEY.equalsIgnoreCase(value.getPropertyName()) || PropertyConstants.SYMBOLIC_KEY.equalsIgnoreCase(value.getPropertyName()))) { return sendToServer(failures, onlineOperationRequired); } } } // It is not legal to modify the state of a lock through a local // call. Check.isTrue(changeRequest.getLockLevel() == LockLevel.UNCHANGED, "changeRequest.getLockLevel() == LockLevel.UNCHANGED"); //$NON-NLS-1$ final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromItemSpec(changeRequest.getItemSpec(), wp, lv, pc, ParsedItemSpecOptions.NONE, failureList); if (null == parsedItemSpec) { continue; } for (final WorkspaceLocalItem lvEntry : parsedItemSpec.expandFrom(lv, pc, failureList)) { final String targetServerItem = pc.getTargetServerItemForLocalVersion(lvEntry); if (!duplicatesFilter.add(lvEntry)) { continue; } LocalPendingChange pcEntry = pc.getByLocalVersion(lvEntry); if (null != pcEntry && pcEntry.isDelete()) { final String format = Messages .getString("LocalDataAccessLayer.IncompatibleChangeExceptionFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(format, targetServerItem); failureList.add(new Failure(message, FailureCodes.INCOMPATIBLE_CHANGE_EXCEPTION, SeverityType.ERROR, changeRequest.getItemSpec().getItem())); continue; } if (pc.getRecursiveChangeTypeForLocalVersion(lvEntry).contains(ChangeType.DELETE)) { final String changedItem = changeRequest.getItemSpec().getItem(); failureList.add(createPendingParentDeleteFailure(targetServerItem, changedItem)); continue; } // OK, we need to modify or create the pending change for this // item. if (null == pcEntry) { Check.isTrue(lvEntry.isCommitted(), "Local version is uncommitted but has no pending change."); //$NON-NLS-1$ pcEntry = new LocalPendingChange(lvEntry, targetServerItem, ChangeType.PROPERTY); } else { pcEntry.setChangeType(pcEntry.getChangeType().combine(ChangeType.PROPERTY)); } // Merge with existing properties for save pcEntry.setPropertyValues(PropertyUtils.mergePendingValues(pcEntry.getPropertyValues(), changeRequest.getProperties())); pc.pendChange(pcEntry); // Create the GetOperation for this pending change. if (!silent) { // The get operation only has properties that match the // filters final GetOperation getop = lvEntry.toGetOperation(pcEntry, itemPropertyFilters); getop.setChangeType(pc.getRecursiveChangeTypeForLocalVersion(lvEntry)); getOps.add(getop); } } } for (final Failure failure : failureList) { failure.setRequestType(RequestType.PROPERTY); } failures.set(failureList.toArray(new Failure[failureList.size()])); return getOps.toArray(new GetOperation[getOps.size()]); }
From source file:io.warp10.continuum.egress.EgressFetchHandler.java
/** * Output a text version of fetched data. Deduplication is done on the fly so we don't decode twice. * /*from w ww . ja va 2s . co m*/ */ private static void textDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean raw, boolean dedup, boolean signed, boolean showAttributes, AtomicReference<Metadata> lastMeta, AtomicLong lastCount, boolean sortMeta) throws IOException { String name = null; Map<String, String> labels = null; StringBuilder sb = new StringBuilder(); Metadata lastMetadata = lastMeta.get(); long currentCount = lastCount.get(); while (iter.hasNext()) { GTSDecoder decoder = iter.next(); if (!decoder.next()) { continue; } long toDecodeCount = Long.MAX_VALUE; if (timespan < 0) { Metadata meta = decoder.getMetadata(); if (!meta.equals(lastMetadata)) { lastMetadata = meta; currentCount = 0; } toDecodeCount = Math.max(0, -timespan - currentCount); } // // Only display the class + labels if they have changed since the previous GTS // Map<String, String> lbls = decoder.getLabels(); // // Compute the new name // boolean displayName = false; if (null == name || (!name.equals(decoder.getName()) || !labels.equals(lbls))) { displayName = true; name = decoder.getName(); labels = lbls; sb.setLength(0); GTSHelper.encodeName(sb, name); sb.append("{"); boolean first = true; if (sortMeta) { lbls = new TreeMap<String, String>(lbls); } for (Entry<String, String> entry : lbls.entrySet()) { // // Skip owner/producer labels and any other 'private' labels // if (!signed) { if (Constants.PRODUCER_LABEL.equals(entry.getKey())) { continue; } if (Constants.OWNER_LABEL.equals(entry.getKey())) { continue; } } if (!first) { sb.append(","); } GTSHelper.encodeName(sb, entry.getKey()); sb.append("="); GTSHelper.encodeName(sb, entry.getValue()); first = false; } sb.append("}"); if (showAttributes) { Metadata meta = decoder.getMetadata(); if (meta.getAttributesSize() > 0) { if (sortMeta) { meta.setAttributes(new TreeMap<String, String>(meta.getAttributes())); } GTSHelper.labelsToString(sb, meta.getAttributes()); } else { sb.append("{}"); } } } long timestamp = 0L; long location = GeoTimeSerie.NO_LOCATION; long elevation = GeoTimeSerie.NO_ELEVATION; Object value = null; boolean dup = true; long decoded = 0; do { if (toDecodeCount == decoded) { break; } // FIXME(hbs): only display the results which match the authorized (according to token) timerange and geo zones // // Filter out any value not in the time range // long newTimestamp = decoder.getTimestamp(); if (newTimestamp > now || (timespan >= 0 && newTimestamp <= (now - timespan))) { continue; } // // TODO(hbs): filter out values with no location or outside the selected geozone when a geozone was set // long newLocation = decoder.getLocation(); long newElevation = decoder.getElevation(); Object newValue = decoder.getValue(); dup = true; if (dedup) { if (location != newLocation || elevation != newElevation) { dup = false; } else { if (null == newValue) { // Consider nulls as duplicates (can't happen!) dup = false; } else if (newValue instanceof Number) { if (!((Number) newValue).equals(value)) { dup = false; } } else if (newValue instanceof String) { if (!((String) newValue).equals(value)) { dup = false; } } else if (newValue instanceof Boolean) { if (!((Boolean) newValue).equals(value)) { dup = false; } } } } decoded++; location = newLocation; elevation = newElevation; timestamp = newTimestamp; value = newValue; if (raw) { if (!dedup || !dup) { pw.println(GTSHelper.tickToString(sb, timestamp, location, elevation, value)); } } else { // Display the name only if we have at least one value to display // We force 'dup' to be false when we must show the name if (displayName) { pw.println(GTSHelper.tickToString(sb, decoder.getTimestamp(), decoder.getLocation(), decoder.getElevation(), decoder.getValue())); displayName = false; dup = false; } else { if (!dedup || !dup) { pw.print("="); pw.println(GTSHelper.tickToString(timestamp, location, elevation, value)); } } } } while (decoder.next()); // Update currentcount if (timespan < 0) { currentCount += decoded; } // Print any remaining value if (dedup && dup) { if (raw) { pw.println(GTSHelper.tickToString(sb, timestamp, location, elevation, value)); } else { pw.print("="); pw.println(GTSHelper.tickToString(timestamp, location, elevation, value)); } } // // If displayName is still true it means we should have displayed the name but no value matched, // so set name to null so we correctly display the name for the next decoder if it has values // if (displayName) { name = null; } } lastMeta.set(lastMetadata); lastCount.set(currentCount); }
From source file:io.warp10.continuum.egress.EgressFetchHandler.java
private static void jsonDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean dedup, boolean signed, AtomicReference<Metadata> lastMeta, AtomicLong lastCount) throws IOException { String name = null;/*from w ww .ja v a 2 s.c o m*/ Map<String, String> labels = null; pw.print("["); boolean hasValues = false; Metadata lastMetadata = lastMeta.get(); long currentCount = lastCount.get(); try { StringBuilder sb = new StringBuilder(); JsonSerializer serializer = new JsonSerializerFactory().create(); boolean firstgts = true; long mask = (long) (Math.random() * Long.MAX_VALUE); while (iter.hasNext()) { GTSDecoder decoder = iter.next(); if (dedup) { decoder = decoder.dedup(); } if (!decoder.next()) { continue; } long toDecodeCount = Long.MAX_VALUE; if (timespan < 0) { Metadata meta = decoder.getMetadata(); if (!meta.equals(lastMetadata)) { lastMetadata = meta; currentCount = 0; } toDecodeCount = Math.max(0, -timespan - currentCount); } // // Only display the class + labels if they have changed since the previous GTS // Map<String, String> lbls = decoder.getLabels(); // // Compute the new name // boolean displayName = false; if (null == name || (!name.equals(decoder.getName()) || !labels.equals(lbls))) { displayName = true; name = decoder.getName(); labels = lbls; sb.setLength(0); sb.append("{\"c\":"); //sb.append(gson.toJson(name)); sb.append(serializer.serialize(name)); boolean first = true; sb.append(",\"l\":{"); for (Entry<String, String> entry : lbls.entrySet()) { // // Skip owner/producer labels and any other 'private' labels // if (!signed) { if (Constants.PRODUCER_LABEL.equals(entry.getKey())) { continue; } if (Constants.OWNER_LABEL.equals(entry.getKey())) { continue; } } if (!first) { sb.append(","); } //sb.append(gson.toJson(entry.getKey())); sb.append(serializer.serialize(entry.getKey())); sb.append(":"); //sb.append(gson.toJson(entry.getValue())); sb.append(serializer.serialize(entry.getValue())); first = false; } sb.append("}"); sb.append(",\"a\":{"); first = true; for (Entry<String, String> entry : decoder.getMetadata().getAttributes().entrySet()) { if (!first) { sb.append(","); } //sb.append(gson.toJson(entry.getKey())); sb.append(serializer.serialize(entry.getKey())); sb.append(":"); //sb.append(gson.toJson(entry.getValue())); sb.append(serializer.serialize(entry.getValue())); first = false; } sb.append("}"); sb.append(",\"i\":\""); sb.append(decoder.getLabelsId() & mask); sb.append("\",\"v\":["); } long decoded = 0L; do { if (toDecodeCount == decoded) { break; } // FIXME(hbs): only display the results which match the authorized (according to token) timerange and geo zones // // Filter out any value not in the time range // if (decoder.getTimestamp() > now || (timespan >= 0 && decoder.getTimestamp() <= (now - timespan))) { continue; } decoded++; // // TODO(hbs): filter out values with no location or outside the selected geozone when a geozone was set // // Display the name only if we have at least one value to display if (displayName) { if (!firstgts) { pw.print("]},"); } pw.print(sb.toString()); firstgts = false; displayName = false; } else { pw.print(","); } hasValues = true; pw.print("["); pw.print(decoder.getTimestamp()); if (GeoTimeSerie.NO_LOCATION != decoder.getLocation()) { double[] latlon = GeoXPLib.fromGeoXPPoint(decoder.getLocation()); pw.print(","); pw.print(latlon[0]); pw.print(","); pw.print(latlon[1]); } if (GeoTimeSerie.NO_ELEVATION != decoder.getElevation()) { pw.print(","); pw.print(decoder.getElevation()); } pw.print(","); Object value = decoder.getValue(); if (value instanceof Number) { pw.print(value); } else if (value instanceof Boolean) { pw.print(Boolean.TRUE.equals(value) ? "true" : "false"); } else { //pw.print(gson.toJson(value.toString())); pw.print(serializer.serialize(value.toString())); } pw.print("]"); } while (decoder.next()); if (timespan < 0) { currentCount += decoded; } // // If displayName is still true it means we should have displayed the name but no value matched, // so set name to null so we correctly display the name for the next decoder if it has values // if (displayName) { name = null; } } } catch (Throwable t) { throw t; } finally { if (hasValues) { pw.print("]}"); } pw.print("]"); } lastMeta.set(lastMetadata); lastCount.set(currentCount); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java
/** * Gets all of the pending changes and candidate changes. * * @param specs//from ww w.ja v a2 s .c o m * {@link ItemSpec}s to get pending changes for (must not be * <code>null</code> or empty) * @param includeDownloadInfo * if true, the server will include the information needed to * download files. Only set this to true if you are going to be * downloading the files using the objects that are returned. The * call will be faster and require less bandwidth when this parameter * is false (default for overloads that don't specify it) * @param candidateChanges * a a reference to receive the candidate changes (must not be * <code>null</code>) * @param itemPropertyFilters * a list of property names to return on the pending change object if * they exist (may be <code>null</code>) * @return a pending set including all the pending changes, * <code>null</code> or an empty array if there are no pending * changes for the given specs */ public PendingChange[] getPendingChangesWithCandidates(final ItemSpec[] itemSpecs, final boolean includeDownloadInfo, final AtomicReference<PendingChange[]> candidateChanges, String[] itemPropertyFilters) { Check.notNullOrEmpty(itemSpecs, "itemSpecs"); //$NON-NLS-1$ Check.notNull(candidateChanges, "candidateChanges"); //$NON-NLS-1$ // Using web service directly so merge filters configured on client itemPropertyFilters = client.mergeWithDefaultItemPropertyFilters(itemPropertyFilters); final AtomicReference<Failure[]> failures = new AtomicReference<Failure[]>(); final PendingSet[] pendingSets = getClient().getWebServiceLayer().queryPendingSets(getName(), getOwnerName(), getName(), getOwnerName(), itemSpecs, includeDownloadInfo, failures, true, itemPropertyFilters); Check.isTrue(pendingSets.length <= 1, "How did we get more than 1 pending set for a workspace?"); //$NON-NLS-1$ // report failures getClient().reportFailures(this, failures.get()); if (pendingSets.length == 0) { candidateChanges.set(new PendingChange[0]); return new PendingChange[0]; } else { candidateChanges.set(pendingSets[0].getCandidatePendingChanges()); if (candidateChanges.get() == null) { candidateChanges.set(new PendingChange[0]); } return pendingSets[0].getPendingChanges(); } }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.LocalDataAccessLayer.java
/** * * * * @param workspace// w w w . j a v a2s .c om * @param lv * @param pc * @param changeRequests * @param silent * @param failures * @return */ public static GetOperation[] pendEdit(final Workspace workspace, final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv, final LocalPendingChangesTable pc, final ChangeRequest[] changeRequests, final boolean silent, final AtomicReference<Failure[]> failures, final String[] itemPropertyFilters) { Check.notNull(workspace, "workspace"); //$NON-NLS-1$ Check.notNullOrEmpty(changeRequests, "changeRequests"); //$NON-NLS-1$ final List<Failure> failureList = new ArrayList<Failure>(); final List<GetOperation> getOps = new ArrayList<GetOperation>(); final Set<WorkspaceLocalItem> duplicatesFilter = new HashSet<WorkspaceLocalItem>(); for (final ChangeRequest changeRequest : changeRequests) { if (null == changeRequest) { continue; } // It is not legal to modify the state of a lock through a local // call. Check.isTrue(changeRequest.getLockLevel() == LockLevel.UNCHANGED, "changeRequest.getLockLevel() == LockLevel.UNCHANGED"); //$NON-NLS-1$ final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromItemSpec(changeRequest.getItemSpec(), wp, lv, pc, ParsedItemSpecOptions.NONE, failureList); if (null == parsedItemSpec) { continue; } for (final WorkspaceLocalItem lvEntry : parsedItemSpec.expandFrom(lv, pc, failureList)) { final String targetServerItem = pc.getTargetServerItemForLocalVersion(lvEntry); if (!duplicatesFilter.add(lvEntry)) { continue; } if (lvEntry.isDirectory()) { if (RecursionType.NONE == parsedItemSpec.getRecursionType()) { final String format = Messages.getString("LocalDataAccessLayer.FolderEditExceptionFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(format, targetServerItem); failureList.add(new Failure(message, FailureCodes.NOT_ALLOWED_ON_FOLDER_EXCEPTION, SeverityType.ERROR, changeRequest.getItemSpec().getItem())); } continue; } LocalPendingChange pcEntry = pc.getByLocalVersion(lvEntry); if (null != pcEntry && pcEntry.isDelete()) { final String format = Messages .getString("LocalDataAccessLayer.IncompatibleChangeExceptionFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(format, targetServerItem); failureList.add(new Failure(message, FailureCodes.INCOMPATIBLE_CHANGE_EXCEPTION, SeverityType.ERROR, changeRequest.getItemSpec().getItem())); continue; } if (pc.getRecursiveChangeTypeForLocalVersion(lvEntry).contains(ChangeType.DELETE)) { final String changedItem = changeRequest.getItemSpec().getItem(); failureList.add(createPendingParentDeleteFailure(targetServerItem, changedItem)); continue; } if (null != pcEntry && pcEntry.isAdd() && VersionControlConstants.ENCODING_UNCHANGED == changeRequest.getEncoding()) { final String format = Messages .getString("LocalDataAccessLayer.IncompatibleChangeExceptionFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(format, targetServerItem); failureList.add(new Failure(message, FailureCodes.INCOMPATIBLE_CHANGE_EXCEPTION, SeverityType.ERROR, changeRequest.getItemSpec().getItem())); continue; } // OK, we need to modify or create the pending change for this // item. if (null == pcEntry) { Check.isTrue(lvEntry.isCommitted(), "Local version is uncommitted but has no pending change."); //$NON-NLS-1$ pcEntry = new LocalPendingChange(lvEntry, targetServerItem, ChangeType.EDIT); } else { pcEntry.setChangeType(pcEntry.getChangeType().combine(ChangeType.EDIT)); } if (changeRequest.getProperties() != null) { for (final PropertyValue value : changeRequest.getProperties()) { if (PropertyConstants.SYMBOLIC_KEY.equalsIgnoreCase(value.getPropertyName())) { pcEntry.setChangeType(pcEntry.getChangeType().combine(ChangeType.PROPERTY)); // Merge with existing properties for save pcEntry.setPropertyValues(PropertyUtils.mergePendingValues(pcEntry.getPropertyValues(), changeRequest.getProperties())); } } } if (VersionControlConstants.ENCODING_UNCHANGED != changeRequest.getEncoding()) { pcEntry.setEncoding(changeRequest.getEncoding()); pcEntry.setChangeType(pcEntry.getChangeType().combine(ChangeType.ENCODING)); } pc.pendChange(pcEntry); // Create the GetOperation for this pending change. if (!silent) { final GetOperation getop = lvEntry.toGetOperation(pcEntry, itemPropertyFilters); getop.setChangeType(pc.getRecursiveChangeTypeForLocalVersion(lvEntry)); getOps.add(getop); } } } for (final Failure failure : failureList) { failure.setRequestType(RequestType.EDIT); } failures.set(failureList.toArray(new Failure[failureList.size()])); return getOps.toArray(new GetOperation[getOps.size()]); }
From source file:org.apache.geode.management.internal.cli.commands.CreateRegionCommand.java
@CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP) @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION) @ResourceOperation(resource = ResourcePermission.Resource.DATA, operation = ResourcePermission.Operation.MANAGE) public Result createRegion( @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true, help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath, @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT, help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut, @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM, optionContext = ConverterHint.REGION_PATH, help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom, @CliOption(key = { CliStrings.GROUP, CliStrings.GROUPS }, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups, @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists, // the following should all be in alphabetical order according to // their key string @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID, help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds, @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER, help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener, @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER, help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader, @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER, help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter, @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH, optionContext = ConverterHint.REGION_PATH, help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith, @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR, help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor, @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL, help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel, @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE, help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore, @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION, help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation, @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED, help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled, @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED, help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled, @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED, help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled, @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED, help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled, @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION, help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation, @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS, help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction, @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID, help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds, @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT, help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint, @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY, help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory, @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true", help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap, @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER, help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction, @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY, help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay, @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES, help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies, @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY, help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay, @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY, help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory, @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS, help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets, @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT, help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint // NOTICE: keep the region attributes params in alphabetical order ) {/*w w w. j a va2 s . c o m*/ Result result; AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); try { InternalCache cache = getCache(); if (regionShortcut != null && useAttributesFrom != null) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED); } else if (regionShortcut == null && useAttributesFrom == null) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUTESFROM_IS_REQUIRED); } validateRegionPathAndParent(cache, regionPath); RegionCommandsUtils.validateGroups(cache, groups); RegionFunctionArgs.ExpirationAttrs entryIdle = null; if (entryExpirationIdleTime != null) { entryIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime, entryExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs entryTTL = null; if (entryExpirationTTL != null) { entryTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL, entryExpirationTTLAction); } RegionFunctionArgs.ExpirationAttrs regionIdle = null; if (regionExpirationIdleTime != null) { regionIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime, regionExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs regionTTL = null; if (regionExpirationTTL != null) { regionTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL, regionExpirationTTLAction); } RegionFunctionArgs regionFunctionArgs; if (useAttributesFrom != null) { if (!regionExists(cache, useAttributesFrom)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND, CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom)); } FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult = getRegionAttributes( cache, useAttributesFrom); RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes(); // give preference to user specified plugins than the ones retrieved from other region String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0 ? cacheListener : regionAttributesResult.getCacheListenerClasses(); String cacheLoaderClass = cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass(); String cacheWriterClass = cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass(); regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation, enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass, asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled, concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies, prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled, regionAttributes, partitionResolver); if (regionAttributes.getPartitionAttributes() == null && regionFunctionArgs.hasPartitionAttributes()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION, regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " " + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION, useAttributesFrom)); } } else { regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom, skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation, enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled, concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies, prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap, mcastEnabled, partitionResolver); if (!regionShortcut.name().startsWith("PARTITION") && regionFunctionArgs.hasPartitionAttributes()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION, regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " " + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION, useAttributesFrom)); } } // Do we prefer to validate or authorize first? validateRegionFunctionArgs(cache, regionFunctionArgs); if (isPersistentShortcut(regionFunctionArgs.getRegionShortcut()) || isAttributePersistent(regionFunctionArgs.getRegionAttributes())) { getSecurityService().authorize(ResourcePermission.Resource.CLUSTER, ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK); } Set<DistributedMember> membersToCreateRegionOn; if (groups != null && groups.length != 0) { membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups); // have only normal members from the group membersToCreateRegionOn .removeIf(distributedMember -> ((InternalDistributedMember) distributedMember) .getVmKind() == DistributionManager.LOCATOR_DM_TYPE); } else { membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache); } if (membersToCreateRegionOn.isEmpty()) { return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE); } ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE, regionFunctionArgs, membersToCreateRegionOn); @SuppressWarnings("unchecked") List<CliFunctionResult> regionCreateResults = (List<CliFunctionResult>) resultCollector.getResult(); TabularResultData tabularResultData = ResultBuilder.createTabularResultData(); final String errorPrefix = "ERROR: "; for (CliFunctionResult regionCreateResult : regionCreateResults) { boolean success = regionCreateResult.isSuccessful(); tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName()); tabularResultData.accumulate("Status", (success ? "" : errorPrefix) + regionCreateResult.getMessage()); if (success) { xmlEntity.set(regionCreateResult.getXmlEntity()); } } result = ResultBuilder.buildResult(tabularResultData); verifyDistributedRegionMbean(cache, regionPath); } catch (IllegalArgumentException | IllegalStateException e) { LogWrapper.getInstance().info(e.getMessage()); result = ResultBuilder.createUserErrorResult(e.getMessage()); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups)); } return result; }