List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:cl.gisred.android.MedidorActivity.java
private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) { final AtomicReference<String> resp = new AtomicReference<>(""); if (bSave) {/* w ww . ja v 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(MedidorActivity.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(MedidorActivity.this, resp.get(), Toast.LENGTH_SHORT).show(); } }); } }); } } } else { resp.set("Cancelado"); Toast.makeText(MedidorActivity.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); menuMedidorActions.setVisibility(View.VISIBLE); fabShowDialog.setVisibility(View.GONE); dialogCrear.dismiss(); if (oLyAddGraphs != null) oLyAddGraphs.setVisible(true); }
From source file:cl.gisred.android.LectorActivity.java
private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) { final AtomicReference<String> resp = new AtomicReference<>(""); if (bSave) {/*from w w w.j a v a2s . co 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(LectorActivity.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(LectorActivity.this, resp.get(), Toast.LENGTH_SHORT).show(); } }); } }); } } } else { resp.set("Cancelado"); Toast.makeText(LectorActivity.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); menuLectorActions.setVisibility(View.VISIBLE); fabShowDialog.setVisibility(View.GONE); dialogCrear.dismiss(); if (oLyAddGraphs != null) oLyAddGraphs.setVisible(true); }
From source file:cl.gisred.android.RegEquipoActivity.java
private void cerrarFormLimit(boolean bSave, View v) { // TODO Usar Layer Indicada bSave = false;//from w w w . j a v a2s .co m if (bSave) { final AtomicReference<String> resp = new AtomicReference<>(""); if (!validarZoneLimit(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", oText.getIdObjeto()); oUbicacion = oText.getPoint(); } else if (oText.getId() == R.id.txtTramoBt) { objectMap.put("id_tramo", oText.getText().toString()); } } } } objectMap.put("empresa", empresa); objectMap.put("modulo", modulo); Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap); Graphic[] adds = { newFeatureGraphic }; LyRetRegEquipo.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 (LyRetRegEquipo != null) LyRetRegEquipo.setVisible(true); }
From source file:cl.gisred.android.MicroMedidaActivity.java
private void cerrarFormLimit(boolean bSave, View v) { if (bSave) {//ww w .j a va2s .c o m final AtomicReference<String> resp = new AtomicReference<>(""); if (!validarZoneLimit(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", oText.getIdObjeto()); oUbicacion = oText.getPoint(); } else if (oText.getId() == R.id.txtTramoBt) { objectMap.put("id_tramo", oText.getText().toString()); } } } } objectMap.put("empresa", empresa); objectMap.put("modulo", modulo); Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap); Graphic[] adds = { newFeatureGraphic }; LyAddZoneLimit.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 (LyAddZoneLimit != null) LyAddZoneLimit.setVisible(true); }
From source file:cl.gisred.android.MantCatastroActivity.java
private void cerrarFormMant(boolean bSave, View v) { if (bSave) {/*from w ww . 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(Spinner.class)) { Spinner oSpinner = (Spinner) view; String sValue = oSpinner.getSelectedItem().toString(); if (oSpinner.getId() == R.id.spinnerElement) objectMap.put("elemento", sValue); else if (oSpinner.getId() == R.id.spinnerDiagnostic) objectMap.put("diagnostico", sValue); else if (oSpinner.getId() == R.id.spinnerMaterial) objectMap.put("material", sValue); else if (oSpinner.getId() == R.id.spinnerCriticidad) objectMap.put("criticidad", sValue); } } objectMap.put("id_padre", idNodo); objectMap.put("rotulo", rotulo); objectMap.put("empresa", empresa); objectMap.put("estado", "Informado"); Graphic newFeatureGraphic = new Graphic(oUbicacionForm, null, objectMap); Graphic[] adds = { newFeatureGraphic }; LyAddMantCatastro.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(MantCatastroActivity.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(MantCatastroActivity.this, resp.get(), Toast.LENGTH_SHORT).show(); } }); } }); } } bMapTap = false; oUbicacionForm = 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); fabShowForm.setVisibility(View.GONE); formMant.dismiss(); if (LyAddMantCatastro != null) LyAddMantCatastro.setVisible(true); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.LocalDataAccessLayer.java
/** * Updates the local copy of the local version table for this workspace in * accordance with the update requests provided by the localVersionUpdates * parameter.//from w ww. ja v a 2 s .c o m * * * @param workspace * Workspace whose local version table is being updated * @param wp * Workspace properties table * @param lv * Local version table * @param pc * Pending changes table (const) * @param localVersionUpdates * Update requests for the local version table * @param persistedDisplacedBaselines * (optional) A HashSet instance for persisting the set of displaced * baselines across multiple calls to UpdateLocalVersion. Used for * circular renames which may cross calls to UpdateLocalVersion * @param updateMissingBaselines * The set of ClientLocalVersionUpdate objects which were processed * successfully but which had no baseline file GUID when one was * needed. A baseline file GUID was generated for these items and the * caller should download the required baselines to ensure offline * content is available. */ public static void updateLocalVersion(final Workspace workspace, final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv, final LocalPendingChangesTable pc, final ILocalVersionUpdate[] localVersionUpdates, final Set<byte[]> persistedDisplacedBaselines, final AtomicReference<IPopulatableLocalVersionUpdate[]> updateMissingBaselines) { final boolean setFileTimeToCheckin = workspace.getOptions().contains(WorkspaceOptions.SET_FILE_TO_CHECKIN); final List<IPopulatableLocalVersionUpdate> updatesMissingBaselinesList = new ArrayList<IPopulatableLocalVersionUpdate>(); Set<byte[]> displacedBaselines = persistedDisplacedBaselines; if (displacedBaselines == null) { displacedBaselines = new TreeSet<byte[]>(new BaselineFileGUIDComparer()); } for (final ILocalVersionUpdate update : localVersionUpdates) { if (update instanceof MoveUncommittedLocalVersionUpdate) { handleMoveUncommittedUpdate(wp, lv, (MoveUncommittedLocalVersionUpdate) update); } else if (update instanceof InitiallyDeletedLocalVersionUpdate) { final InitiallyDeletedLocalVersionUpdate idUpdate = (InitiallyDeletedLocalVersionUpdate) update; final boolean updateIsMissingBaseline = handleInitiallyDeletedLocalVersionUpdate(wp, lv, pc, idUpdate, setFileTimeToCheckin, displacedBaselines); if (updateIsMissingBaseline) { updatesMissingBaselinesList.add(idUpdate); } } else if (update instanceof ClientLocalVersionUpdate) { final ClientLocalVersionUpdate cUpdate = (ClientLocalVersionUpdate) update; final boolean updateIsMissingBaseline = handleClientLocalVersionUpdate(wp, lv, pc, cUpdate, setFileTimeToCheckin, displacedBaselines); if (updateIsMissingBaseline) { updatesMissingBaselinesList.add(cUpdate); } } } // If the caller did not provide a collection for displaced baselines to // persist in beyond the lifetime of this call, then we need to go ahead // and purge the displaced baselines now. if (null == persistedDisplacedBaselines) { for (final byte[] baselineFileGuid : displacedBaselines) { wp.deleteBaseline(baselineFileGuid); } } // Return the set of updates which were missing baseline file GUIDs to // the caller so that they can download them. updateMissingBaselines.set(updatesMissingBaselinesList .toArray(new IPopulatableLocalVersionUpdate[updatesMissingBaselinesList.size()])); }
From source file:io.warp10.continuum.egress.EgressFetchHandler.java
private static void wrapperDump(PrintWriter pw, GTSDecoderIterator iter, boolean dedup, boolean signed, byte[] fetchPSK, long timespan, AtomicReference<Metadata> lastMeta, AtomicLong lastCount) throws IOException { if (!signed) { throw new IOException("Unsigned request."); }/* w w w . j a va 2 s.co m*/ // Labels for Sensision Map<String, String> labels = new HashMap<String, String>(); StringBuilder sb = new StringBuilder(); Metadata lastMetadata = lastMeta.get(); long currentCount = lastCount.get(); while (iter.hasNext()) { GTSDecoder decoder = iter.next(); if (dedup) { decoder = decoder.dedup(); } if (!decoder.next()) { continue; } long toDecodeCount = Long.MAX_VALUE; if (timespan < 0) { Metadata meta = decoder.getMetadata(); if (!meta.equals(lastMetadata)) { lastMetadata = meta; currentCount = 0; } toDecodeCount = Math.max(0, -timespan - currentCount); } GTSEncoder encoder = decoder.getEncoder(true); if (encoder.getCount() > toDecodeCount) { // We have too much data, shrink the encoder GTSEncoder enc = new GTSEncoder(); enc.safeSetMetadata(decoder.getMetadata()); while (decoder.next() && toDecodeCount > 0) { enc.addValue(decoder.getTimestamp(), decoder.getLocation(), decoder.getElevation(), decoder.getValue()); toDecodeCount--; } encoder = enc; } if (timespan < 0) { currentCount += encoder.getCount(); } if (encoder.size() <= 0) { continue; } // // Build a GTSWrapper // GTSWrapper wrapper = GTSWrapperHelper.fromGTSEncoderToGTSWrapper(encoder, true); // GTSWrapper wrapper = new GTSWrapper(); // wrapper.setBase(encoder.getBaseTimestamp()); // wrapper.setMetadata(encoder.getMetadata()); // wrapper.setCount(encoder.getCount()); // wrapper.setEncoded(encoder.getBytes()); // // Serialize the wrapper // TSerializer serializer = new TSerializer(new TCompactProtocol.Factory()); byte[] data = null; try { data = serializer.serialize(wrapper); } catch (TException te) { throw new IOException(te); } // // Output is GTSWrapperId <WSP> HASH <WSP> GTSWrapper // pw.write(Hex.encodeHex(GTSWrapperHelper.getId(wrapper))); pw.write(' '); if (null != fetchPSK) { // // Compute HMac for the wrapper // long hash = SipHashInline.hash24(fetchPSK, data); // // Output the MAC before the data, as hex digits // pw.write(Hex.encodeHex(Longs.toByteArray(hash))); } else { pw.write('-'); } pw.write(' '); // // Base64 encode the wrapper // OrderPreservingBase64.encodeToWriter(data, pw); pw.write('\r'); pw.write('\n'); // // Sensision metrics // labels.clear(); labels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, wrapper.getMetadata().getLabels().get(Constants.APPLICATION_LABEL)); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS, Sensision.EMPTY_LABELS, 1); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_PERAPP, labels, 1); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_SIZE, Sensision.EMPTY_LABELS, data.length); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_SIZE_PERAPP, labels, data.length); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_DATAPOINTS, Sensision.EMPTY_LABELS, wrapper.getCount()); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_DATAPOINTS_PERAPP, labels, wrapper.getCount()); } lastMeta.set(lastMetadata); lastCount.set(currentCount); }
From source file:cl.gisred.android.MantCatastroActivity.java
private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) { final AtomicReference<String> resp = new AtomicReference<>(""); if (bSave) {/*w w w . j a 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(MantCatastroActivity.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(MantCatastroActivity.this, resp.get(), Toast.LENGTH_SHORT) .show(); } }); } }); } } } else { resp.set("Cancelado"); Toast.makeText(MantCatastroActivity.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:de.schildbach.pte.AbstractEfaProvider.java
protected NearbyLocationsResult xmlCoordRequest(final EnumSet<LocationType> types, final int lat, final int lon, final int maxDistance, final int maxStations) throws IOException { final HttpUrl.Builder url = coordEndpoint.newBuilder(); appendXmlCoordRequestParameters(url, types, lat, lon, maxDistance, maxStations); final AtomicReference<NearbyLocationsResult> result = new AtomicReference<>(); final HttpClient.Callback callback = new HttpClient.Callback() { @Override//w w w .j a v a 2s .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 = enterItdRequest(pp); XmlPullUtil.enter(pp, "itdCoordInfoRequest"); XmlPullUtil.enter(pp, "itdCoordInfo"); XmlPullUtil.enter(pp, "coordInfoRequest"); XmlPullUtil.skipExit(pp, "coordInfoRequest"); final List<Location> locations = new ArrayList<>(); if (XmlPullUtil.optEnter(pp, "coordInfoItemList")) { while (XmlPullUtil.test(pp, "coordInfoItem")) { final String type = XmlPullUtil.attr(pp, "type"); final LocationType locationType; if ("STOP".equals(type)) locationType = LocationType.STATION; else if ("POI_POINT".equals(type)) locationType = LocationType.POI; else throw new IllegalStateException("unknown type: " + type); String id = XmlPullUtil.optAttr(pp, "stateless", null); if (id == null) id = XmlPullUtil.attr(pp, "id"); final String name = normalizeLocationName(XmlPullUtil.optAttr(pp, "name", null)); final String place = normalizeLocationName(XmlPullUtil.optAttr(pp, "locality", null)); XmlPullUtil.enter(pp, "coordInfoItem"); // FIXME this is always only one coordinate final List<Point> path = processItdPathCoordinates(pp); final Point coord = path != null ? path.get(0) : null; XmlPullUtil.skipExit(pp, "coordInfoItem"); if (name != null) locations.add(new Location(locationType, id, coord, place, name)); } XmlPullUtil.skipExit(pp, "coordInfoItemList"); } result.set(new NearbyLocationsResult(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:org.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { if (msg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) msg; if ("/favicon.ico".equals(req.getUri())) { sendError(ctx, NOT_FOUND, "Gremlin Server doesn't have a favicon.ico"); ReferenceCountUtil.release(msg); return; }/*from ww w .ja v a 2 s . c o m*/ if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } if (req.getMethod() != GET && req.getMethod() != POST) { sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString()); ReferenceCountUtil.release(msg); return; } final Quartet<String, Map<String, Object>, String, Map<String, String>> requestArguments; try { requestArguments = getRequestArguments(req); } catch (IllegalArgumentException iae) { sendError(ctx, BAD_REQUEST, iae.getMessage()); ReferenceCountUtil.release(msg); return; } final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json"); final Pair<String, MessageTextSerializer> serializer = chooseSerializer(acceptString); if (null == serializer) { sendError(ctx, BAD_REQUEST, String.format("no serializer for requested Accept header: %s", acceptString)); ReferenceCountUtil.release(msg); return; } final String origin = req.headers().get(ORIGIN); final boolean keepAlive = isKeepAlive(req); // not using the req any where below here - assume it is safe to release at this point. ReferenceCountUtil.release(msg); try { logger.debug("Processing request containing script [{}] and bindings of [{}] on {}", requestArguments.getValue0(), requestArguments.getValue1(), Thread.currentThread().getName()); final ChannelPromise promise = ctx.channel().newPromise(); final AtomicReference<Object> resultHolder = new AtomicReference<>(); promise.addListener(future -> { // if failed then the error was already written back to the client as part of the eval future // processing of the exception if (future.isSuccess()) { logger.debug( "Preparing HTTP response for request with script [{}] and bindings of [{}] with result of [{}] on [{}]", requestArguments.getValue0(), requestArguments.getValue1(), resultHolder.get(), Thread.currentThread().getName()); final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, (ByteBuf) resultHolder.get()); response.headers().set(CONTENT_TYPE, serializer.getValue0()); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // handle cors business if (origin != null) response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin); if (!keepAlive) { ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); ctx.writeAndFlush(response); } } }); final Timer.Context timerContext = evalOpTimer.time(); final Bindings bindings; try { bindings = createBindings(requestArguments.getValue1(), requestArguments.getValue3()); } catch (IllegalStateException iae) { sendError(ctx, BAD_REQUEST, iae.getMessage()); ReferenceCountUtil.release(msg); return; } // provide a transform function to serialize to message - this will force serialization to occur // in the same thread as the eval. after the CompletableFuture is returned from the eval the result // is ready to be written as a ByteBuf directly to the response. nothing should be blocking here. final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(requestArguments.getValue0(), requestArguments.getValue2(), bindings, FunctionUtils.wrapFunction(o -> { // stopping the timer here is roughly equivalent to where the timer would have been stopped for // this metric in other contexts. we just want to measure eval time not serialization time. timerContext.stop(); logger.debug( "Transforming result of request with script [{}] and bindings of [{}] with result of [{}] on [{}]", requestArguments.getValue0(), requestArguments.getValue1(), o, Thread.currentThread().getName()); final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID()) .code(ResponseStatusCode.SUCCESS).result(IteratorUtils.asList(o)).create(); // http server is sessionless and must handle commit on transactions. the commit occurs // before serialization to be consistent with how things work for websocket based // communication. this means that failed serialization does not mean that you won't get // a commit to the database attemptCommit(requestArguments.getValue3(), graphManager, settings.strictTransactionManagement); try { return Unpooled.wrappedBuffer(serializer.getValue1() .serializeResponseAsString(responseMessage).getBytes(UTF8)); } catch (Exception ex) { logger.warn(String.format("Error during serialization for %s", responseMessage), ex); throw ex; } })); evalFuture.exceptionally(t -> { sendError(ctx, INTERNAL_SERVER_ERROR, String.format("Error encountered evaluating script: %s", requestArguments.getValue0()), Optional.of(t)); promise.setFailure(t); return null; }); evalFuture.thenAcceptAsync(r -> { // now that the eval/serialization is done in the same thread - complete the promise so we can // write back the HTTP response on the same thread as the original request resultHolder.set(r); promise.setSuccess(); }, gremlinExecutor.getExecutorService()); } catch (Exception ex) { // tossed to exceptionCaught which delegates to sendError method final Throwable t = ExceptionUtils.getRootCause(ex); throw new RuntimeException(null == t ? ex : t); } } }