Example usage for java.util.concurrent.atomic AtomicReference get

List of usage examples for java.util.concurrent.atomic AtomicReference get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference get.

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:cl.gisred.android.InspActivity.java

private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) {
    final AtomicReference<String> resp = new AtomicReference<>("");

    if (bSave) {/*from  www  . ja va 2  s .c o  m*/
        if (!validarVista(viewDialog)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {
            switch (idResLayoutSelect) {
            case R.layout.dialog_poste:
                oLyAddGraphs = LyAddPoste;
                break;
            case R.layout.dialog_direccion:
                oLyAddGraphs = LyAddDireccion;
                break;
            case R.layout.dialog_cliente:
                oLyAddGraphs = LyAddCliente;
                break;
            case R.layout.dialog_cliente_cnr:
                oLyAddGraphs = LyAddClienteCnr;
                break;
            }

            if (oLyAddGraphs != null) {
                View oView = getLayoutValidate(viewDialog);
                Util oUtil = new Util(oUbicacion);

                ArrayList<Map<String, Object>> oAttrToSave = oUtil.getAttrAddByView(oView, idResLayoutSelect,
                        empresa);

                Map<String, Object> attributes = oAttrToSave.get(0);
                Graphic newFeatureGraphic = new Graphic(oUbicacion, null, attributes);
                Graphic[] adds = { newFeatureGraphic };

                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                        || idResLayoutSelect == R.layout.dialog_cliente) {
                    addsUnion = Util.addAttrUnionPoint(oAttrToSave, oUbicacion);
                }

                oLyAddGraphs.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());

                                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                                        || idResLayoutSelect == R.layout.dialog_cliente)
                                    LyAddUnion.applyEdits(addsUnion, null, null, callBackUnion());

                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        Util.showConfirmation(InspActivity.this, resp.get());
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        resp.set("Error al grabar: " + throwable.getLocalizedMessage());
                        Log.w("onError", resp.get());

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(InspActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(InspActivity.this, resp.get(), Toast.LENGTH_LONG).show();
    }

    bMapTap = false;

    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);

    oUbicacion = null;
    if (bVerCapas)
        toogleCapas(fabVerCapas);
    //setLayerAddToggle(false);
    menuMultipleActions.setVisibility(View.VISIBLE);
    menuInspeccionActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}

From source file:de.schildbach.pte.AbstractEfaProvider.java

protected SuggestLocationsResult mobileStopfinderRequest(final Location constraint) throws IOException {
    final HttpUrl.Builder url = stopFinderEndpoint.newBuilder();
    appendStopfinderRequestParameters(url, constraint, "XML");
    final AtomicReference<SuggestLocationsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override// w  w  w . j a  v a  2  s .c  o  m
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                final XmlPullParser pp = parserFactory.newPullParser();
                pp.setInput(body.byteStream(), null); // Read encoding from XML declaration
                final ResultHeader header = enterEfa(pp);

                final List<SuggestedLocation> locations = new ArrayList<>();

                XmlPullUtil.require(pp, "sf");
                if (XmlPullUtil.optEnter(pp, "sf")) {
                    while (XmlPullUtil.optEnter(pp, "p")) {
                        final String name = normalizeLocationName(XmlPullUtil.valueTag(pp, "n"));
                        final String u = XmlPullUtil.valueTag(pp, "u");
                        if (!"sf".equals(u))
                            throw new RuntimeException("unknown usage: " + u);
                        final String ty = XmlPullUtil.valueTag(pp, "ty");
                        final LocationType type;
                        if ("stop".equals(ty))
                            type = LocationType.STATION;
                        else if ("poi".equals(ty))
                            type = LocationType.POI;
                        else if ("loc".equals(ty))
                            type = LocationType.COORD;
                        else if ("street".equals(ty))
                            type = LocationType.ADDRESS;
                        else if ("singlehouse".equals(ty))
                            type = LocationType.ADDRESS;
                        else
                            throw new RuntimeException("unknown type: " + ty);

                        XmlPullUtil.enter(pp, "r");

                        final String id = XmlPullUtil.valueTag(pp, "id");
                        XmlPullUtil.optValueTag(pp, "gid", null);
                        XmlPullUtil.valueTag(pp, "stateless");
                        XmlPullUtil.valueTag(pp, "omc");
                        final String place = normalizeLocationName(XmlPullUtil.optValueTag(pp, "pc", null));
                        XmlPullUtil.valueTag(pp, "pid");
                        final Point coord = parseCoord(XmlPullUtil.optValueTag(pp, "c", null));

                        XmlPullUtil.skipExit(pp, "r");

                        final String qal = XmlPullUtil.optValueTag(pp, "qal", null);
                        final int quality = qal != null ? Integer.parseInt(qal) : 0;

                        XmlPullUtil.skipExit(pp, "p");

                        final Location location = new Location(type, type == LocationType.STATION ? id : null,
                                coord, place, name);
                        final SuggestedLocation locationAndQuality = new SuggestedLocation(location, quality);
                        locations.add(locationAndQuality);
                    }

                    XmlPullUtil.skipExit(pp, "sf");
                }

                result.set(new SuggestLocationsResult(header, locations));
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + bodyPeek, x);
            }
        }
    };

    if (httpPost)
        httpClient.getInputStream(callback, url.build(), url.build().encodedQuery(),
                "application/x-www-form-urlencoded", httpReferer);
    else
        httpClient.getInputStream(callback, url.build(), httpReferer);

    return result.get();
}

From source file:de.schildbach.pte.AbstractEfaProvider.java

protected QueryDeparturesResult queryDeparturesMobile(final String stationId, final @Nullable Date time,
        final int maxDepartures, final boolean equivs) throws IOException {
    final HttpUrl.Builder url = departureMonitorEndpoint.newBuilder();
    appendXsltDepartureMonitorRequestParameters(url, stationId, time, maxDepartures, equivs);
    final AtomicReference<QueryDeparturesResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override//w ww.j a  v a2  s  .  c  o  m
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                final XmlPullParser pp = parserFactory.newPullParser();
                pp.setInput(body.byteStream(), null); // Read encoding from XML declaration
                final ResultHeader header = enterEfa(pp);
                final QueryDeparturesResult r = new QueryDeparturesResult(header);

                XmlPullUtil.require(pp, "dps");
                if (XmlPullUtil.optEnter(pp, "dps")) {
                    final Calendar plannedDepartureTime = new GregorianCalendar(timeZone);
                    final Calendar predictedDepartureTime = new GregorianCalendar(timeZone);

                    while (XmlPullUtil.optEnter(pp, "dp")) {
                        // misc
                        /* final String stationName = */normalizeLocationName(XmlPullUtil.valueTag(pp, "n"));
                        /* final boolean isRealtime = */XmlPullUtil.valueTag(pp, "realtime").equals("1");

                        XmlPullUtil.optSkip(pp, "dt");

                        // time
                        parseMobileSt(pp, plannedDepartureTime, predictedDepartureTime);

                        final LineDestination lineDestination = parseMobileM(pp, true);

                        XmlPullUtil.enter(pp, "r");
                        final String assignedId = XmlPullUtil.valueTag(pp, "id");
                        XmlPullUtil.valueTag(pp, "a");
                        final Position position = parsePosition(XmlPullUtil.optValueTag(pp, "pl", null));
                        XmlPullUtil.skipExit(pp, "r");

                        /* final Point positionCoordinate = */parseCoord(
                                XmlPullUtil.optValueTag(pp, "c", null));

                        // TODO messages

                        StationDepartures stationDepartures = findStationDepartures(r.stationDepartures,
                                assignedId);
                        if (stationDepartures == null) {
                            stationDepartures = new StationDepartures(
                                    new Location(LocationType.STATION, assignedId),
                                    new ArrayList<Departure>(maxDepartures), null);
                            r.stationDepartures.add(stationDepartures);
                        }

                        stationDepartures.departures.add(new Departure(plannedDepartureTime.getTime(),
                                predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY)
                                        ? predictedDepartureTime.getTime()
                                        : null,
                                lineDestination.line, position, lineDestination.destination, null, null));

                        XmlPullUtil.skipExit(pp, "dp");
                    }

                    XmlPullUtil.skipExit(pp, "dps");

                    result.set(r);
                } else {
                    result.set(new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION));
                }
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + bodyPeek, x);
            }
        }
    };

    if (httpPost)
        httpClient.getInputStream(callback, url.build(), url.build().encodedQuery(),
                "application/x-www-form-urlencoded", httpReferer);
    else
        httpClient.getInputStream(callback, url.build(), httpReferer);

    return result.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();/*from  w  w  w  .  j  ava2s. 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:it.anyplace.sync.bep.BlockPusher.java

public FileUploadObserver pushFile(final DataSource dataSource, @Nullable FileInfo fileInfo,
        final String folder, final String path) {
    checkArgument(connectionHandler.hasFolder(folder),
            "supplied connection handler %s will not share folder %s", connectionHandler, folder);
    checkArgument(fileInfo == null || equal(fileInfo.getFolder(), folder));
    checkArgument(fileInfo == null || equal(fileInfo.getPath(), path));
    try {/*w w w  .  ja  v  a 2 s  . c o  m*/
        final ExecutorService monitoringProcessExecutorService = Executors.newCachedThreadPool();
        final long fileSize = dataSource.getSize();
        final Set<String> sentBlocks = Sets.newConcurrentHashSet();
        final AtomicReference<Exception> uploadError = new AtomicReference<>();
        final AtomicBoolean isCompleted = new AtomicBoolean(false);
        final Object updateLock = new Object();
        final Object listener = new Object() {
            @Subscribe
            public void handleRequestMessageReceivedEvent(RequestMessageReceivedEvent event) {
                BlockExchageProtos.Request request = event.getMessage();
                if (equal(request.getFolder(), folder) && equal(request.getName(), path)) {
                    try {
                        final String hash = BaseEncoding.base16().encode(request.getHash().toByteArray());
                        logger.debug("handling block request = {}:{}-{} ({})", request.getName(),
                                request.getOffset(), request.getSize(), hash);
                        byte[] data = dataSource.getBlock(request.getOffset(), request.getSize(), hash);
                        checkNotNull(data, "data not found for hash = %s", hash);
                        final Future future = connectionHandler.sendMessage(
                                Response.newBuilder().setCode(BlockExchageProtos.ErrorCode.NO_ERROR)
                                        .setData(ByteString.copyFrom(data)).setId(request.getId()).build());
                        monitoringProcessExecutorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    future.get();
                                    sentBlocks.add(hash);
                                    synchronized (updateLock) {
                                        updateLock.notifyAll();
                                    }
                                    //TODO retry on error, register error and throw on watcher
                                } catch (InterruptedException ex) {
                                    //return and do nothing
                                } catch (ExecutionException ex) {
                                    uploadError.set(ex);
                                    synchronized (updateLock) {
                                        updateLock.notifyAll();
                                    }
                                }
                            }
                        });
                    } catch (Exception ex) {
                        logger.error("error handling block request", ex);
                        connectionHandler.sendMessage(Response.newBuilder()
                                .setCode(BlockExchageProtos.ErrorCode.GENERIC).setId(request.getId()).build());
                        uploadError.set(ex);
                        synchronized (updateLock) {
                            updateLock.notifyAll();
                        }
                    }
                }
            }
        };
        connectionHandler.getEventBus().register(listener);
        logger.debug("send index update for file = {}", path);
        final Object indexListener = new Object() {

            @Subscribe
            public void handleIndexRecordAquiredEvent(IndexHandler.IndexRecordAquiredEvent event) {
                if (equal(event.getFolder(), folder)) {
                    for (FileInfo fileInfo : event.getNewRecords()) {
                        if (equal(fileInfo.getPath(), path)
                                && equal(fileInfo.getHash(), dataSource.getHash())) { //TODO check not invalid
                            //                                sentBlocks.addAll(dataSource.getHashes());
                            isCompleted.set(true);
                            synchronized (updateLock) {
                                updateLock.notifyAll();
                            }
                        }
                    }
                }
            }
        };
        if (indexHandler != null) {
            indexHandler.getEventBus().register(indexListener);
        }
        final IndexUpdate indexUpdate = sendIndexUpdate(folder,
                BlockExchageProtos.FileInfo.newBuilder().setName(path).setSize(fileSize)
                        .setType(BlockExchageProtos.FileInfoType.FILE).addAllBlocks(dataSource.getBlocks()),
                fileInfo == null ? null : fileInfo.getVersionList()).getRight();
        final FileUploadObserver messageUploadObserver = new FileUploadObserver() {
            @Override
            public void close() {
                logger.debug("closing upload process");
                try {
                    connectionHandler.getEventBus().unregister(listener);
                    monitoringProcessExecutorService.shutdown();
                    if (indexHandler != null) {
                        indexHandler.getEventBus().unregister(indexListener);
                    }
                } catch (Exception ex) {
                }
                if (closeConnection && connectionHandler != null) {
                    connectionHandler.close();
                }
                if (indexHandler != null) {
                    FileInfo fileInfo = indexHandler.pushRecord(indexUpdate.getFolder(),
                            Iterables.getOnlyElement(indexUpdate.getFilesList()));
                    logger.info("sent file info record = {}", fileInfo);
                }
            }

            @Override
            public double getProgress() {
                return isCompleted() ? 1d : sentBlocks.size() / ((double) dataSource.getHashes().size());
            }

            @Override
            public String getProgressMessage() {
                return (Math.round(getProgress() * 1000d) / 10d) + "% " + sentBlocks.size() + "/"
                        + dataSource.getHashes().size();
            }

            @Override
            public boolean isCompleted() {
                //                    return sentBlocks.size() == dataSource.getHashes().size();
                return isCompleted.get();
            }

            @Override
            public double waitForProgressUpdate() throws InterruptedException {
                synchronized (updateLock) {
                    updateLock.wait();
                }
                if (uploadError.get() != null) {
                    throw new RuntimeException(uploadError.get());
                }
                return getProgress();
            }

            @Override
            public DataSource getDataSource() {
                return dataSource;
            }

        };
        return messageUploadObserver;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:cl.gisred.android.RegEquipoActivity.java

private void cerrarFormCrear(boolean bSave, View v) {
    // TODO Usar Layer Indicada
    bSave = false;// w w  w  . ja  v a2s . c  om
    if (bSave) {

        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 };
            LyAgrRegEquipo.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(RegEquipoActivity.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(RegEquipoActivity.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 (LyAgrRegEquipo != null)
        LyAgrRegEquipo.setVisible(true);
}

From source file:cl.gisred.android.MicroMedidaActivity.java

private void cerrarFormCrear(boolean bSave, View v) {
    if (bSave) {/*from w  w  w  .java  2  s.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.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java

/**
 * Reconciles a local workspace with the server.
 *
 *
 * @param reconcileMissingLocalItems/*from  w w w . j a  v a 2s. co m*/
 *        True to remove local version rows for items that no longer exist
 *        on disk
 * @param AtomicBboolean
 */
public void reconcile(final boolean reconcileMissingLocalItems,
        final AtomicBoolean pendingChangesUpdatedByServer) {
    pendingChangesUpdatedByServer.set(false);
    if (WorkspaceLocation.LOCAL != this.getLocation()) {
        // No work to do.
        return;
    }

    final AtomicReference<Failure[]> failures = new AtomicReference<Failure[]>();

    LocalDataAccessLayer.reconcileLocalWorkspace(this, client.getWebServiceLayer(), false,
            reconcileMissingLocalItems, failures, pendingChangesUpdatedByServer);

    client.reportFailures(this, failures.get());
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java

/**
 * Gets all of the pending changes and candidate changes.
 *
 * @param specs//from   w  w  w  . j a  va  2  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.soapextensions.Workspace.java

/**
 * Pends a change that reverts the contents of one or more items to a
 * previous version's contents. <!-- Event Origination Info -->
 * <p>//ww w .j  a  v  a2 s.  co m
 * This method is an <b>core event origination point</b>. The
 * {@link EventSource} object that accompanies each event fired by this
 * method describes the execution context (current thread, etc.) when and
 * where this method was invoked.
 *
 * @param itemSpecs
 *        the items to roll back (must not be <code>null</code>)
 * @param itemVersionSpec
 *        the version of the given item specs (may be null)
 * @param versionFrom
 *        the version to rollback from (not sure) (must not be
 *        <code>null</code>)
 * @param versionTo
 *        the version to rollback to (not sure) (must not be
 *        <code>null</code>)
 * @param lockLevel
 *        the lock level for the pending change (must not be
 *        <code>null</code>)
 * @param options
 *        rollback options (must not be <code>null</code>)
 * @param itemPropertyFilters
 *        a list of versioned item properties to return with each get
 *        operation (may be <code>null</code>)
 * @since TFS 2010
 */
public GetStatus rollback(final ItemSpec[] itemSpecs, final VersionSpec itemVersionSpec,
        final VersionSpec versionFrom, final VersionSpec versionTo, final LockLevel lockLevel,
        final RollbackOptions options, String[] itemPropertyFilters) {
    Check.notNull(versionFrom, "versionFrom"); //$NON-NLS-1$
    Check.notNull(versionTo, "versionTo"); //$NON-NLS-1$
    Check.notNull(lockLevel, "lockLevel"); //$NON-NLS-1$
    Check.notNull(options, "options"); //$NON-NLS-1$

    client.getEventEngine().fireOperationStarted(
            new RollbackOperationStartedEvent(EventSource.newFromHere(), this, itemSpecs, options));

    GetStatus status = null;

    try {
        // Using web service directly so merge filters configured on client
        itemPropertyFilters = client.mergeWithDefaultItemPropertyFilters(itemPropertyFilters);

        final AtomicReference<Failure[]> failuresHolder = new AtomicReference<Failure[]>();
        final AtomicReference<Conflict[]> conflictsHolder = new AtomicReference<Conflict[]>();
        final AtomicReference<ChangePendedFlags> changePendedFlagsHolder = new AtomicReference<ChangePendedFlags>();

        final GetOperation[] operations = getClient().getWebServiceLayer().rollback(getName(), getOwnerName(),
                itemSpecs, itemVersionSpec, versionFrom, versionTo, options, lockLevel, conflictsHolder,
                failuresHolder, null, itemPropertyFilters, changePendedFlagsHolder);

        final Failure[] failures = failuresHolder.get();
        Conflict[] conflicts = conflictsHolder.get();
        int nonResolvedConflicts = 0;
        int resolvedConflicts = 0;
        final ChangePendedFlags changePendedFlags = changePendedFlagsHolder.get();

        /*
         * Match up these getOps and rollback details (returned as Conflict
         * objects). The conflicts with matching getOps have already been
         * resolved.
         */
        final Map<Integer, Conflict> itemIDConflictMap = new HashMap<Integer, Conflict>();
        final List<String> conflictPaths = new ArrayList<String>();
        for (final Conflict conflict : conflicts) {
            if (conflict.isResolved()) {
                itemIDConflictMap.put(new Integer(conflict.getYourItemID()), conflict);
            } else {
                conflictPaths.add(conflict.getServerPath());
            }
        }

        /*
         * Set the merge details for each of the resolved conflicts we found
         * previously.
         */
        for (final GetOperation operation : operations) {
            final Conflict conflict = itemIDConflictMap.get(new Integer(operation.getItemID()));

            if (conflict != null) {
                operation.setMergeDetails(conflict);
            }
        }

        if (isLocal()) {
            // We want to auto resolve conflicts if the option is set
            if (!options.contains(RollbackOptions.NO_AUTO_RESOLVE)) {
                if (getClient().getServiceLevel().getValue() < WebServiceLevel.TFS_2012_1.getValue()) {
                    /*
                     * The download urls for base files were not populated
                     * on conflicts in pre 2012 servers. Let's call
                     * QueryConflicts now so that we have that information
                     */
                    conflicts = queryConflicts(conflictPaths.toArray(new String[conflictPaths.size()]), false);
                }

                /*
                 * Try to resolve any AutoResolve candidates and add
                 * failures to the unresolved conflicts list.
                 */
                final Conflict[] remainingConflicts = getClient().autoResolveValidConflicts(this, conflicts,
                        AutoResolveOptions.ALL_SILENT);

                resolvedConflicts = conflicts.length - remainingConflicts.length;
                conflicts = remainingConflicts;
            }

            /*
             * Fire events for rollback operations that did not get resolved
             * by the server. The others will get fired in get.cs as they
             * are processed.
             */
            for (final Conflict conflict : conflicts) {
                if (conflict.getResolution() == Resolution.NONE) {
                    // The pending change arg is null because of the
                    // conflict.
                    getClient().getEventEngine()
                            .fireMerging(new MergingEvent(EventSource.newFromHere(), conflict, this, false,
                                    null, OperationStatus.CONFLICT, ChangeType.NONE, true,
                                    new PropertyValue[0]));

                    nonResolvedConflicts++;
                }
            }

            final GetEngine getEngine = new GetEngine(getClient());

            status = getEngine.processGetOperations(this, ProcessType.ROLLBACK, operations, GetOptions.NONE,
                    changePendedFlags);

            status.setNumConflicts(status.getNumConflicts() + nonResolvedConflicts);
            status.setNumResolvedConflicts(resolvedConflicts);
        } else if (operations.length > 0) {
            getClient().getEventEngine()
                    .fireNonFatalError(new NonFatalErrorEvent(EventSource.newFromHere(), getClient(),
                            new Exception(MessageFormat.format(Messages.getString(
                                    "Workspace.OperationCompletedForRemoteWorkspaceButGetRequiredFormat"), //$NON-NLS-1$
                                    getDisplayName()))));
        }

        if (status == null) {
            status = new GetStatus();
            status.setNumOperations(operations.length);
        }

        if (changePendedFlags.contains(ChangePendedFlags.WORKING_FOLDER_MAPPINGS_UPDATED)) {
            invalidateMappings();
        }

        getClient().reportFailures(this, failures);

        for (final Failure failure : failures) {
            status.addFailure(failure);
        }
    } finally {
        getClient().getEventEngine().fireOperationCompleted(new RollbackOperationCompletedEvent(
                EventSource.newFromHere(), this, itemSpecs, options, status));

        Workstation.getCurrent(getClient().getConnection().getPersistenceStoreProvider())
                .notifyForWorkspace(this, Notification.VERSION_CONTROL_PENDING_CHANGES_CHANGED);
    }

    return status;
}