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

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

Introduction

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

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.WebServiceLayerLocalWorkspaces.java

@Override
public PendingSet[] queryPendingSets(final String localWorkspaceName, final String localWorkspaceOwner,
        final String queryWorkspaceName, final String ownerName, final ItemSpec[] itemSpecs,
        final boolean generateDownloadUrls, final AtomicReference<Failure[]> failures,
        final boolean includeCandidates, final String[] itemPropertyFilters) {
    Workspace localWorkspace;//from   w w  w.j a  v  a 2  s .co m

    if ((localWorkspace = getLocalWorkspace(queryWorkspaceName, ownerName)) != null) {
        boolean nonExecuteSymlinkBitPropertyChange = false;
        if (itemPropertyFilters != null) {
            for (final String filter : itemPropertyFilters) {
                /*
                 * Not using wildcard matching here: just because a wildcard
                 * _does_ match the executable key _doesn't_ mean it
                 * wouldn't match others on the server. So only consider a
                 * direct match against the executable key to keep
                 * processing locally.
                 */
                if (PropertyValue.comparePropertyNames(PropertyConstants.EXECUTABLE_KEY, filter) != 0
                        && PropertyValue.comparePropertyNames(PropertyConstants.SYMBOLIC_KEY, filter) != 0) {
                    nonExecuteSymlinkBitPropertyChange = true;
                    break;
                }
            }
        }

        boolean okayToPerformLocalQuery = true;
        if ((null != localWorkspaceName && null != localWorkspaceOwner
                && (Workspace.matchName(localWorkspaceName, queryWorkspaceName) == false
                        || localWorkspace.ownerNameMatches(localWorkspaceOwner) == false))
                || nonExecuteSymlinkBitPropertyChange) {
            // Caller claims he is sending local paths in the itemspecs, and
            // that the local paths are from a different workspace or that
            // he is requesting properties that must go to the server
            okayToPerformLocalQuery = false;
        }

        PendingSet[] pendingSets;
        if (okayToPerformLocalQuery) {
            pendingSets = LocalDataAccessLayer.queryPendingChanges(localWorkspace, itemSpecs, failures,
                    includeCandidates, null, 0, itemPropertyFilters);
        } else {
            reconcileIfLocal(queryWorkspaceName, ownerName);
            reconcileIfAnyLocalItemSpecs(localWorkspaceName, localWorkspaceOwner, itemSpecs);

            // Through this codepath, local workspace pending changes are
            // returned verbatim. So we must reconcile before calling

            try {
                if (getServiceLevel().getValue() >= WebServiceLevel.TFS_2012_QU1.getValue()) {
                    final _Repository5Soap_QueryPendingSetsWithLocalWorkspacesResponse response = getRepository5()
                            .queryPendingSetsWithLocalWorkspaces(localWorkspaceName, localWorkspaceOwner,
                                    queryWorkspaceName, ownerName,
                                    (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, itemSpecs),
                                    generateDownloadUrls, itemPropertyFilters,
                                    VersionControlConstants.MAX_SERVER_PATH_SIZE);
                    failures.set((Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures()));
                    pendingSets = (PendingSet[]) WrapperUtils.wrap(PendingSet.class,
                            response.getQueryPendingSetsWithLocalWorkspacesResult());
                } else {
                    final _Repository4Soap_QueryPendingSetsWithLocalWorkspacesResponse response = getRepository4()
                            .queryPendingSetsWithLocalWorkspaces(localWorkspaceName, localWorkspaceOwner,
                                    queryWorkspaceName, ownerName,
                                    (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, itemSpecs),
                                    generateDownloadUrls, itemPropertyFilters);
                    failures.set((Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures()));
                    pendingSets = (PendingSet[]) WrapperUtils.wrap(PendingSet.class,
                            response.getQueryPendingSetsWithLocalWorkspacesResult());
                }
            } catch (final ProxyException e) {
                throw VersionControlExceptionMapper.map(e);
            }
        }

        for (final PendingSet ps : pendingSets) {
            ps.setPendingSetDetails();
        }
        return pendingSets;
    }

    // Through this codepath, local workspace pending changes are masked to
    // show only the "lock" bit
    return super.queryPendingSets(localWorkspaceName, localWorkspaceOwner, queryWorkspaceName, ownerName,
            itemSpecs, generateDownloadUrls, failures, includeCandidates, itemPropertyFilters);
}

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

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

    if (bSave) {//from  w w w . j a v a  2s  . 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(LectorInspActivity.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(LectorInspActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(LectorInspActivity.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);
    if (bIngCliente)
        menuMultipleActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}

From source file:org.apache.brooklyn.location.jclouds.JcloudsLocation.java

protected LoginCredentials waitForSshable(final ComputeService computeService, final NodeMetadata node,
        Optional<HostAndPort> hostAndPortOverride, List<LoginCredentials> credentialsToTry, ConfigBag setup) {
    String waitForSshable = setup.get(WAIT_FOR_SSHABLE);
    checkArgument(!"false".equalsIgnoreCase(waitForSshable),
            "waitForReachable called despite waitForSshable=%s for %s", waitForSshable, node);
    checkArgument(credentialsToTry.size() > 0, "waitForReachable called without credentials for %s", node);

    Duration timeout = null;/* w  w  w .ja  v a 2 s.c o m*/
    try {
        timeout = Duration.parse(waitForSshable);
    } catch (Exception e) {
        // normal if 'true'; just fall back to default
    }
    if (timeout == null) {
        timeout = Duration.parse(WAIT_FOR_SSHABLE.getDefaultValue());
    }

    Set<String> users = Sets.newLinkedHashSet();
    for (LoginCredentials creds : credentialsToTry) {
        users.add(creds.getUser());
    }
    String user = (users.size() == 1) ? Iterables.getOnlyElement(users)
            : "{" + Joiner.on(",").join(users) + "}";
    String vmIp = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getHostText()
            : getFirstReachableAddress(node, setup);
    if (vmIp == null)
        LOG.warn("Unable to extract IP for " + node + " (" + setup.getDescription()
                + "): subsequent connection attempt will likely fail");
    int vmPort = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getPortOrDefault(22) : 22;

    String connectionDetails = user + "@" + vmIp + ":" + vmPort;
    final HostAndPort hostAndPort = hostAndPortOverride.isPresent() ? hostAndPortOverride.get()
            : HostAndPort.fromParts(vmIp, vmPort);
    final AtomicReference<LoginCredentials> credsSuccessful = new AtomicReference<LoginCredentials>();

    // Don't use config that relates to the final user credentials (those have nothing to do 
    // with the initial credentials of the VM returned by the cloud provider).
    ConfigBag sshProps = ConfigBag.newInstanceCopying(setup);
    sshProps.remove("password");
    sshProps.remove("privateKeyData");
    sshProps.remove("privateKeyFile");
    sshProps.remove("privateKeyPassphrase");

    final Map<SshMachineLocation, LoginCredentials> machinesToTry = Maps.newLinkedHashMap();
    for (LoginCredentials creds : credentialsToTry) {
        machinesToTry.put(createTemporarySshMachineLocation(hostAndPort, creds, sshProps), creds);
    }
    try {
        Callable<Boolean> checker = new Callable<Boolean>() {
            public Boolean call() {
                for (Map.Entry<SshMachineLocation, LoginCredentials> entry : machinesToTry.entrySet()) {
                    SshMachineLocation machine = entry.getKey();
                    int exitstatus = machine
                            .execScript(
                                    ImmutableMap.of(SshTool.PROP_SSH_TRIES_TIMEOUT.getName(),
                                            Duration.THIRTY_SECONDS.toMilliseconds(),
                                            SshTool.PROP_SSH_TRIES.getName(), 1),
                                    "check-connectivity", ImmutableList.of("true"));
                    boolean success = (exitstatus == 0);
                    if (success) {
                        credsSuccessful.set(entry.getValue());
                        return true;
                    }
                }
                return false;
            }
        };

        waitForReachable(checker, connectionDetails, credentialsToTry, setup, timeout);
    } finally {
        for (SshMachineLocation machine : machinesToTry.keySet()) {
            getManagementContext().getLocationManager().unmanage(machine);
            Streams.closeQuietly(machine);
        }
    }

    return credsSuccessful.get();
}

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

protected final QueryDeparturesResult xmlStationBoard(final HttpUrl url, final String stationId)
        throws IOException {
    final String normalizedStationId = normalizeStationId(stationId);
    final AtomicReference<QueryDeparturesResult> result = new AtomicReference<>();

    httpClient.getInputStream(new HttpClient.Callback() {

        @Override//from   w  w  w.ja  va2  s.c  o m
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            StringReplaceReader reader = null;
            String firstChars = null;

            // work around unparsable XML
            reader = new StringReplaceReader(body.charStream(), " & ", " &amp; ");
            reader.replace("<b>", " ");
            reader.replace("</b>", " ");
            reader.replace("<u>", " ");
            reader.replace("</u>", " ");
            reader.replace("<i>", " ");
            reader.replace("</i>", " ");
            reader.replace("<br />", " ");
            reader.replace(" ->", " &#x2192;"); // right arrow
            reader.replace(" <-", " &#x2190;"); // left arrow
            reader.replace(" <> ", " &#x2194; "); // left-right arrow
            addCustomReplaces(reader);

            try {
                final XmlPullParserFactory factory = XmlPullParserFactory
                        .newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
                final XmlPullParser pp = factory.newPullParser();
                pp.setInput(reader);

                pp.nextTag();

                final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT);
                final QueryDeparturesResult r = new QueryDeparturesResult(header);

                if (XmlPullUtil.test(pp, "Err")) {
                    final String code = XmlPullUtil.attr(pp, "code");
                    final String text = XmlPullUtil.attr(pp, "text");

                    if (code.equals("H730")) {
                        result.set(new QueryDeparturesResult(header,
                                QueryDeparturesResult.Status.INVALID_STATION));
                        return;
                    }
                    if (code.equals("H890")) {
                        r.stationDepartures.add(
                                new StationDepartures(new Location(LocationType.STATION, normalizedStationId),
                                        Collections.<Departure>emptyList(), null));
                        result.set(r);
                        return;
                    }
                    throw new IllegalArgumentException("unknown error " + code + ", " + text);
                }

                String[] stationPlaceAndName = null;

                if (stationBoardHasStationTable)
                    XmlPullUtil.enter(pp, "StationTable");
                else
                    checkState(!XmlPullUtil.test(pp, "StationTable"));

                if (stationBoardHasLocation) {
                    XmlPullUtil.require(pp, "St");

                    final String evaId = XmlPullUtil.attr(pp, "evaId");
                    if (evaId != null) {
                        if (!evaId.equals(normalizedStationId))
                            throw new IllegalStateException(
                                    "stationId: " + normalizedStationId + ", evaId: " + evaId);

                        final String name = XmlPullUtil.attr(pp, "name");
                        if (name != null)
                            stationPlaceAndName = splitStationName(name.trim());
                    }
                    XmlPullUtil.requireSkip(pp, "St");
                } else {
                    checkState(!XmlPullUtil.test(pp, "St"));
                }

                while (XmlPullUtil.test(pp, "Journey")) {
                    final String fpTime = XmlPullUtil.attr(pp, "fpTime");
                    final String fpDate = XmlPullUtil.attr(pp, "fpDate");
                    final String delay = XmlPullUtil.attr(pp, "delay");
                    final String eDelay = XmlPullUtil.optAttr(pp, "e_delay", null);
                    final String platform = XmlPullUtil.optAttr(pp, "platform", null);
                    // TODO newpl
                    final String targetLoc = XmlPullUtil.optAttr(pp, "targetLoc", null);
                    // TODO hafasname
                    final String dirnr = XmlPullUtil.optAttr(pp, "dirnr", null);
                    final String prod = XmlPullUtil.attr(pp, "prod");
                    final String classStr = XmlPullUtil.optAttr(pp, "class", null);
                    final String dir = XmlPullUtil.optAttr(pp, "dir", null);
                    final String capacityStr = XmlPullUtil.optAttr(pp, "capacity", null);
                    final String depStation = XmlPullUtil.optAttr(pp, "depStation", null);
                    final String delayReason = XmlPullUtil.optAttr(pp, "delayReason", null);
                    // TODO is_reachable
                    // TODO disableTrainInfo
                    // TODO lineFG/lineBG (ZVV)
                    final String administration = normalizeLineAdministration(
                            XmlPullUtil.optAttr(pp, "administration", null));

                    if (!"cancel".equals(delay) && !"cancel".equals(eDelay)) {
                        final Calendar plannedTime = new GregorianCalendar(timeZone);
                        plannedTime.clear();
                        parseXmlStationBoardDate(plannedTime, fpDate);
                        parseXmlStationBoardTime(plannedTime, fpTime);

                        final Calendar predictedTime;
                        if (eDelay != null) {
                            predictedTime = new GregorianCalendar(timeZone);
                            predictedTime.setTimeInMillis(plannedTime.getTimeInMillis());
                            predictedTime.add(Calendar.MINUTE, Integer.parseInt(eDelay));
                        } else if (delay != null) {
                            final Matcher m = P_XML_STATION_BOARD_DELAY.matcher(delay);
                            if (m.matches()) {
                                if (m.group(1) != null) {
                                    predictedTime = new GregorianCalendar(timeZone);
                                    predictedTime.setTimeInMillis(plannedTime.getTimeInMillis());
                                    predictedTime.add(Calendar.MINUTE, Integer.parseInt(m.group(1)));
                                } else {
                                    predictedTime = null;
                                }
                            } else {
                                throw new RuntimeException("cannot parse delay: '" + delay + "'");
                            }
                        } else {
                            predictedTime = null;
                        }

                        final Position position = parsePosition(ParserUtils.resolveEntities(platform));

                        final String destinationName;
                        if (dir != null)
                            destinationName = dir.trim();
                        else if (targetLoc != null)
                            destinationName = targetLoc.trim();
                        else
                            destinationName = null;

                        final Location destination;
                        if (dirnr != null) {
                            final String[] destinationPlaceAndName = splitStationName(destinationName);
                            destination = new Location(LocationType.STATION, dirnr, destinationPlaceAndName[0],
                                    destinationPlaceAndName[1]);
                        } else {
                            destination = new Location(LocationType.ANY, null, null, destinationName);
                        }

                        final Line prodLine = parseLineAndType(prod);
                        final Line line;
                        if (classStr != null) {
                            final Product product = intToProduct(Integer.parseInt(classStr));
                            if (product == null)
                                throw new IllegalArgumentException();
                            // could check for type consistency here
                            final Set<Attr> attrs = prodLine.attrs;
                            if (attrs != null)
                                line = newLine(administration, product, prodLine.label, null,
                                        attrs.toArray(new Line.Attr[0]));
                            else
                                line = newLine(administration, product, prodLine.label, null);
                        } else {
                            final Set<Attr> attrs = prodLine.attrs;
                            if (attrs != null)
                                line = newLine(administration, prodLine.product, prodLine.label, null,
                                        attrs.toArray(new Line.Attr[0]));
                            else
                                line = newLine(administration, prodLine.product, prodLine.label, null);
                        }

                        final int[] capacity;
                        if (capacityStr != null && !"0|0".equals(capacityStr)) {
                            final String[] capacityParts = capacityStr.split("\\|");
                            capacity = new int[] { Integer.parseInt(capacityParts[0]),
                                    Integer.parseInt(capacityParts[1]) };
                        } else {
                            capacity = null;
                        }

                        final String message;
                        if (delayReason != null) {
                            final String msg = delayReason.trim();
                            message = msg.length() > 0 ? msg : null;
                        } else {
                            message = null;
                        }

                        final Departure departure = new Departure(plannedTime.getTime(),
                                predictedTime != null ? predictedTime.getTime() : null, line, position,
                                destination, capacity, message);

                        final Location location;
                        if (!stationBoardCanDoEquivs || depStation == null) {
                            location = new Location(LocationType.STATION, normalizedStationId,
                                    stationPlaceAndName != null ? stationPlaceAndName[0] : null,
                                    stationPlaceAndName != null ? stationPlaceAndName[1] : null);
                        } else {
                            final String[] depPlaceAndName = splitStationName(depStation);
                            location = new Location(LocationType.STATION, null, depPlaceAndName[0],
                                    depPlaceAndName[1]);
                        }

                        StationDepartures stationDepartures = findStationDepartures(r.stationDepartures,
                                location);
                        if (stationDepartures == null) {
                            stationDepartures = new StationDepartures(location, new ArrayList<Departure>(8),
                                    null);
                            r.stationDepartures.add(stationDepartures);
                        }

                        stationDepartures.departures.add(departure);
                    }

                    XmlPullUtil.requireSkip(pp, "Journey");
                }

                if (stationBoardHasStationTable)
                    XmlPullUtil.exit(pp, "StationTable");

                XmlPullUtil.requireEndDocument(pp);

                // sort departures
                for (final StationDepartures stationDepartures : r.stationDepartures)
                    Collections.sort(stationDepartures.departures, Departure.TIME_COMPARATOR);

                result.set(r);
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + firstChars, x);
            }
        }
    }, url);

    return result.get();
}

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

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

    if (bSave) {//from w ww . jav  a  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(CatastroActivity.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(CatastroActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(CatastroActivity.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);
    menuCatastroActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}

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

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

    if (bSave) {// w ww.  ja  v  a  2s .  c  om
        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(MapsActivity.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(MapsActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(MapsActivity.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);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}

From source file:org.apache.hadoop.hbase.regionserver.TestHRegion.java

@Test
public void testBatchPut() throws Exception {
    byte[] b = Bytes.toBytes(getName());
    byte[] cf = Bytes.toBytes(COLUMN_FAMILY);
    byte[] qual = Bytes.toBytes("qual");
    byte[] val = Bytes.toBytes("val");
    this.region = initHRegion(b, getName(), CONF, cf);
    MetricsWALSource source = CompatibilitySingletonFactory.getInstance(MetricsWALSource.class);
    try {// w  w w .  j a v  a2 s  .  c  o  m
        long syncs = metricsAssertHelper.getCounter("syncTimeNumOps", source);
        metricsAssertHelper.assertCounter("syncTimeNumOps", syncs, source);

        LOG.info("First a batch put with all valid puts");
        final Put[] puts = new Put[10];
        for (int i = 0; i < 10; i++) {
            puts[i] = new Put(Bytes.toBytes("row_" + i));
            puts[i].add(cf, qual, val);
        }

        OperationStatus[] codes = this.region.batchMutate(puts);
        assertEquals(10, codes.length);
        for (int i = 0; i < 10; i++) {
            assertEquals(OperationStatusCode.SUCCESS, codes[i].getOperationStatusCode());
        }
        metricsAssertHelper.assertCounter("syncTimeNumOps", syncs + 1, source);

        LOG.info("Next a batch put with one invalid family");
        puts[5].add(Bytes.toBytes("BAD_CF"), qual, val);
        codes = this.region.batchMutate(puts);
        assertEquals(10, codes.length);
        for (int i = 0; i < 10; i++) {
            assertEquals((i == 5) ? OperationStatusCode.BAD_FAMILY : OperationStatusCode.SUCCESS,
                    codes[i].getOperationStatusCode());
        }

        metricsAssertHelper.assertCounter("syncTimeNumOps", syncs + 2, source);

        LOG.info("Next a batch put that has to break into two batches to avoid a lock");
        RowLock rowLock = region.getRowLock(Bytes.toBytes("row_2"));

        MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext(CONF);
        final AtomicReference<OperationStatus[]> retFromThread = new AtomicReference<OperationStatus[]>();
        TestThread putter = new TestThread(ctx) {
            @Override
            public void doWork() throws IOException {
                retFromThread.set(region.batchMutate(puts));
            }
        };
        LOG.info("...starting put thread while holding lock");
        ctx.addThread(putter);
        ctx.startThreads();

        LOG.info("...waiting for put thread to sync first time");
        long startWait = System.currentTimeMillis();
        while (metricsAssertHelper.getCounter("syncTimeNumOps", source) == syncs + 2) {
            Thread.sleep(100);
            if (System.currentTimeMillis() - startWait > 10000) {
                fail("Timed out waiting for thread to sync first minibatch");
            }
        }
        LOG.info("...releasing row lock, which should let put thread continue");
        rowLock.release();
        LOG.info("...joining on thread");
        ctx.stop();
        LOG.info("...checking that next batch was synced");
        metricsAssertHelper.assertCounter("syncTimeNumOps", syncs + 4, source);
        codes = retFromThread.get();
        for (int i = 0; i < 10; i++) {
            assertEquals((i == 5) ? OperationStatusCode.BAD_FAMILY : OperationStatusCode.SUCCESS,
                    codes[i].getOperationStatusCode());
        }

    } finally {
        HRegion.closeHRegion(this.region);
        this.region = null;
    }
}

From source file:org.apache.blur.mapreduce.lib.CsvBlurDriver.java

public static Job setupJob(Configuration configuration, ControllerPool controllerPool,
        AtomicReference<Callable<Void>> ref, String... otherArgs) throws Exception {
    CommandLine cmd = parse(otherArgs);//from w w  w.j a v  a  2 s  . c  o  m
    if (cmd == null) {
        return null;
    }

    final String controllerConnectionStr = cmd.getOptionValue("c");
    final String tableName = cmd.getOptionValue("t");

    final Iface client = controllerPool.getClient(controllerConnectionStr);
    TableDescriptor tableDescriptor = client.describe(tableName);

    Job job = Job.getInstance(configuration, "Blur indexer [" + tableName + "]");
    job.setJarByClass(CsvBlurDriver.class);
    job.setMapperClass(CsvBlurMapper.class);

    if (cmd.hasOption("p")) {
        job.getConfiguration().set(MAPRED_COMPRESS_MAP_OUTPUT, "true");
        String codecStr = cmd.getOptionValue("p");
        COMPRESSION compression;
        try {
            compression = COMPRESSION.valueOf(codecStr.trim().toUpperCase());
        } catch (IllegalArgumentException e) {
            compression = null;
        }
        if (compression == null) {
            job.getConfiguration().set(MAPRED_MAP_OUTPUT_COMPRESSION_CODEC, codecStr.trim());
        } else {
            job.getConfiguration().set(MAPRED_MAP_OUTPUT_COMPRESSION_CODEC, compression.getClassName());
        }
    }
    if (cmd.hasOption("a")) {
        CsvBlurMapper.setAutoGenerateRecordIdAsHashOfData(job, true);
    }
    if (cmd.hasOption("A")) {
        CsvBlurMapper.setAutoGenerateRowIdAsHashOfData(job, true);
    }
    if (cmd.hasOption("S")) {
        job.setInputFormatClass(SequenceFileInputFormat.class);
    } else {
        job.setInputFormatClass(TextInputFormat.class);
    }

    if (cmd.hasOption("C")) {
        if (cmd.hasOption("S")) {
            String[] optionValues = cmd.getOptionValues("C");
            job.setInputFormatClass(CsvBlurCombineSequenceFileInputFormat.class);
            CombineFileInputFormat.setMinInputSplitSize(job, Long.parseLong(optionValues[0]));
            CombineFileInputFormat.setMaxInputSplitSize(job, Long.parseLong(optionValues[1]));
        } else {
            System.err.println("'C' can only be used with option 'S'");
            return null;
        }
    }

    if (cmd.hasOption("i")) {
        for (String input : cmd.getOptionValues("i")) {
            Path path = new Path(input);
            Set<Path> pathSet = recurisvelyGetPathesContainingFiles(path, job.getConfiguration());
            if (pathSet.isEmpty()) {
                FileInputFormat.addInputPath(job, path);
            } else {
                for (Path p : pathSet) {
                    FileInputFormat.addInputPath(job, p);
                }
            }
        }
    }
    // processing the 'I' option
    if (cmd.hasOption("I")) {
        if (cmd.hasOption("C")) {
            System.err.println("'I' and 'C' both parameters can not be used together.");
            return null;
        }
        Option[] options = cmd.getOptions();
        for (Option option : options) {
            if (option.getOpt().equals("I")) {
                String[] values = option.getValues();
                if (values.length < 2) {
                    System.err.println("'I' parameter missing minimum args of (family path*)");
                    return null;
                }
                for (String p : getSubArray(values, 1)) {
                    Path path = new Path(p);
                    CsvBlurMapper.addFamilyPath(job, values[0], path);
                    FileInputFormat.addInputPath(job, path);
                }
            }
        }
    }

    if (cmd.hasOption("s")) {
        CsvBlurMapper.setSeparator(job, StringEscapeUtils.unescapeJava(cmd.getOptionValue("s")));
    }
    if (cmd.hasOption("o")) {
        BlurOutputFormat.setOptimizeInFlight(job, false);
    }
    if (cmd.hasOption("l")) {
        BlurOutputFormat.setIndexLocally(job, false);
    }
    if (cmd.hasOption("b")) {
        int maxDocumentBufferSize = Integer.parseInt(cmd.getOptionValue("b"));
        BlurOutputFormat.setMaxDocumentBufferSize(job, maxDocumentBufferSize);
    }
    // processing the 'd' option
    Option[] options = cmd.getOptions();
    for (Option option : options) {
        if (option.getOpt().equals("d")) {
            String[] values = option.getValues();
            if (values.length < 2) {
                System.err.println("'d' parameter missing minimum args of (family columname*)");
                return null;
            }
            CsvBlurMapper.addColumns(job, values[0], getSubArray(values, 1));
        }
    }
    BlurOutputFormat.setupJob(job, tableDescriptor);
    BlurMapReduceUtil.addDependencyJars(job.getConfiguration(), Splitter.class);
    if (cmd.hasOption("r")) {
        int reducerMultiplier = Integer.parseInt(cmd.getOptionValue("r"));
        BlurOutputFormat.setReducerMultiplier(job, reducerMultiplier);
    }
    final Path output;
    if (cmd.hasOption("out")) {
        output = new Path(cmd.getOptionValue("out"));
    } else {
        UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
        String userName = currentUser.getUserName();
        output = new Path("/user/" + userName + "/.blur-" + System.currentTimeMillis());
    }
    BlurOutputFormat.setOutputPath(job, output);
    if (cmd.hasOption("import")) {
        ref.set(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                client.loadData(tableName, output.toUri().toString());
                return null;
            }
        });
    }
    return job;
}

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

private void cerrarFormCrear(boolean bSave, View v) {
    if (bSave) {//from   ww w  . j  a v  a 2 s  .  c o  m

        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().getGenericSuperclass().equals(EditText.class)) {
                    EditText oText = (EditText) view;

                    if (oText.getId() == R.id.txtProducto) {
                        String oVal = (oText.getText().toString().isEmpty()) ? "0" : oText.getText().toString();
                        objectMap.put("producto", oVal);
                    }
                    if (oText.getId() == R.id.txtPoste)
                        objectMap.put("poste", oText.getText().toString());
                    if (oText.getId() == R.id.txtDireccion)
                        objectMap.put("direccion", oText.getText().toString());

                } else if (view.getClass().getGenericSuperclass().equals(Spinner.class)) {
                    Spinner oSpinner = (Spinner) view;
                    String sValue = oSpinner.getSelectedItem().toString();

                    if (oSpinner.getId() == R.id.spinnerEstado)
                        objectMap.put("estado", sValue);
                    else if (oSpinner.getId() == R.id.spinnerTipoEdif)
                        objectMap.put("tipo_edificacion", sValue);
                }
            }

            Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap);
            Graphic[] adds = { newFeatureGraphic };
            LyAddCatastro.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(CatastroActivity.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(CatastroActivity.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);

    menuMultipleActions.setVisibility(View.VISIBLE);
    menuCatastroActions.setVisibility(View.VISIBLE);
    fabShowForm.setVisibility(View.GONE);
    formCrear.dismiss();

    if (LyAddCatastro != null)
        LyAddCatastro.setVisible(true);
}

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

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

    if (bSave) {//from  www.j a  v a 2 s. com
        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(OtRouteActivity.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(OtRouteActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(OtRouteActivity.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);
    if (bIngCliente)
        menuMultipleActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}