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:cl.gisred.android.MedidorActivity.java

private void cerrarFormCrear(boolean bSave, View v) {
    if (bSave) {//from  w w  w  . j a  v a  2s.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.txtNroMedidor) {
                        String oVal = (oText.getText().toString().isEmpty()) ? "0" : oText.getText().toString();
                        objectMap.put("nro_medidor", oVal);
                    }
                    if (oText.getId() == R.id.txtLectura) {
                        String oVal = (oText.getText().toString().isEmpty()) ? "0" : oText.getText().toString();
                        objectMap.put("lectura_actual", 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.spinnerTipoEdific)
                        objectMap.put("tipo_edificacion", sValue);
                    else if (oSpinner.getId() == R.id.spinnerUser)
                        objectMap.put("lector", sValue);
                }
            }

            Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap);
            Graphic[] adds = { newFeatureGraphic };
            LyAddMedidores.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(MedidorActivity.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(MedidorActivity.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);
    menuMedidorActions.setVisibility(View.VISIBLE);
    fabShowForm.setVisibility(View.GONE);
    formCrear.dismiss();

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

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

private void cerrarFormCrear(boolean bSave, View v) {
    if (bSave) {/*  w ww  .ja v a  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().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);
                    }
                    if (oText.getId() == R.id.txtLectura) {
                        String oVal = (oText.getText().toString().isEmpty()) ? "0" : oText.getText().toString();
                        objectMap.put("lectura_actual", 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.spinnerTipoEdific)
                        objectMap.put("tipo_edificacion", sValue);
                    else if (oSpinner.getId() == R.id.spinnerUser)
                        objectMap.put("lector", sValue);
                }
            }

            Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap);
            Graphic[] adds = { newFeatureGraphic };
            LyAddLectores.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(LectorActivity.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(LectorActivity.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);
    menuLectorActions.setVisibility(View.VISIBLE);
    fabShowForm.setVisibility(View.GONE);
    formCrear.dismiss();

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

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

public void resolveConflicts(final Workspace workspace, final Conflict[] conflicts,
        String[] itemPropertyFilters, final ResolveErrorOptions errorOptions,
        final AtomicReference<Conflict[]> resolvedConflicts) {
    itemPropertyFilters = mergeWithDefaultItemPropertyFilters(itemPropertyFilters);

    resolvedConflicts.set(new Conflict[0]);

    final List<Conflict> allResolvedConflicts = new ArrayList<Conflict>();
    ChangePendedFlags flags = ChangePendedFlags.UNKNOWN;

    final List<Conflict> localConflicts = new ArrayList<Conflict>();
    final List<List<Conflict>> conflictResolveGroups = new ArrayList<List<Conflict>>();
    conflictResolveGroups.add(new ArrayList<Conflict>());

    for (final Conflict conflict : conflicts) {
        try {//from   www. j a va  2s  . com
            /*
             * If the resolution is to ignore the conflict, there's nothing
             * to do.
             */
            if (Resolution.NONE.equals(conflict.getResolution())) {
                continue;
            }

            /*
             * For local conflicts, we must try the get again. For all other
             * conflicts, we must tell the server the conflict resolution
             * details.
             */
            if (ConflictType.LOCAL.equals(conflict.getType())
                    && !Resolution.DELETE_CONFLICT.equals(conflict.getResolution())) {
                localConflicts.add(conflict);
                continue;
            }

            /* Determine which conflict group to add this to. */
            List<Conflict> conflictGroup = conflictResolveGroups.get(conflictResolveGroups.size() - 1);

            // If it is on a folder then force this resolution to run it its
            // own group to prevent
            // possible collisions on getops with children
            if (ItemType.FOLDER.equals(conflict.getYourItemType())
                    || ItemType.FOLDER.equals(conflict.getTheirItemType())
                    || ItemType.FOLDER.equals(conflict.getBaseItemType())) {
                conflictGroup = new ArrayList<Conflict>();
                conflictResolveGroups.add(conflictGroup);

                // Create a new group for the next conflict so that it
                // doesn't get batched with this one.
                conflictResolveGroups.add(new ArrayList<Conflict>());
            } else if (conflictGroup.size() >= 200) {
                conflictGroup = new ArrayList<Conflict>();
                conflictResolveGroups.add(conflictGroup);
            }

            conflictGroup.add(conflict);
        } catch (final RuntimeException e) {
            if (ResolveErrorOptions.THROW_ON_ERROR.equals(errorOptions)) {
                throw e;
            } else if (ResolveErrorOptions.RAISE_WARNINGS_FOR_ERROR.equals(errorOptions)) {
                eventEngine.fireNonFatalError(new NonFatalErrorEvent(EventSource.newFromHere(), this, e));
            }
        }
    }

    if (localConflicts.size() != 0) {
        resolveLocalConflicts(workspace, localConflicts.toArray(new Conflict[localConflicts.size()]),
                errorOptions);
    }

    for (final List<Conflict> conflictGroup : conflictResolveGroups) {
        if (conflictGroup.size() == 0) {
            continue;
        }

        final WorkspaceLock lock = workspace.lock();

        /*
         * Lock over the call to resolve (which may undo a pending change)
         * and the completion of the processing of those get operations.
         * This prevents a scan from occurring in between these two
         * transactions. If a scan were to run, it would pend an edit on the
         * item whose pending change was just undone by Resolve. This also
         * prevents the movement of merged file content into the workspace
         * from triggering a scan.
         */
        try {
            /*
             * We are doing local operation first, so if it fails, we still
             * have conflict on the server. Bugs 317070 and 395476 If server
             * fails to resolve, we have incorrect file content in the
             * workspace, but this is content user wanted anyway Otherwise
             * (server call first, local operation later) we could resolve
             * the conflict but fail to update the local workspace, so user
             * would really do AcceptYours instead of AcceptMerge
             */
            final Map<Integer, String> updatedSourceLocalItems = new HashMap<Integer, String>();

            /*
             * Replace the user's file with the merged version if we
             * accepted the merge and it's valid to merge the content. The
             * caller may set the merged file name even when it's not valid
             * to copy it over (GUI does this).
             */
            for (final Conflict conflict : conflictGroup) {
                String updatedSourceLocalItem = null;

                if (Resolution.ACCEPT_MERGE.equals(conflict.getResolution()) && conflict.canMergeContent()
                        && conflict.getMergedFileName() != null && conflict.getMergedFileName().length() > 0) {
                    if (conflict.getSourceLocalItem() != null) {
                        /*
                         * Rename the temp file to the real file name.
                         * Delete the target since we know source and target
                         * are different (avoids exception handling).
                         */
                        new File(conflict.getSourceLocalItem()).delete();

                        try {
                            FileHelpers.rename(conflict.getMergedFileName(), conflict.getSourceLocalItem());
                        } catch (final IOException e) {
                            throw new RuntimeException(e);
                        }

                        updatedSourceLocalItem = conflict.getSourceLocalItem();
                    } else {
                        Check.isTrue(conflict.getMergedFileName().toLowerCase().contains("temp"), //$NON-NLS-1$
                                "conflict.getMergedFileName().toLowerCase().contains(\"temp\")"); //$NON-NLS-1$

                        /*
                         * Since we don't have a SourceLocalItem, use the
                         * merged file as the source local item
                         */
                        updatedSourceLocalItem = conflict.getMergedFileName();
                    }
                }

                if (null != updatedSourceLocalItem) {
                    /*
                     * In a local workspace, we have the following problem:
                     * Resolve requires a reconcile, and reconcile does a
                     * disk scan We have just placed new content on this
                     * local item, which will cause the disk scan to pend an
                     * edit on the item. Then reconcile sends the edit to
                     * the server, and reconcile undoes the "merge" change
                     * to replace it with "merge, edit". This causes the
                     * conflict to disappear. So, prevent the scanner from
                     * pending an edit on the item, just for this call.
                     */

                    workspace.getWorkspaceWatcher().addSkippedItem(updatedSourceLocalItem);
                    updatedSourceLocalItems.put(conflict.getConflictID(), updatedSourceLocalItem);
                }
            }

            final ResolveConflictHandler handler = new ResolveConflictHandler(this, workspace,
                    updatedSourceLocalItems);

            try {
                webServiceLayer.resolve(workspace.getName(), workspace.getOwnerName(), conflicts,
                        null, /* itemAttributeFilters */
                        itemPropertyFilters, errorOptions, handler, handler);
            } catch (final Exception e) {
                for (final Conflict conflict : conflicts) {
                    final String updatedSourceLocalItem = updatedSourceLocalItems.get(conflict.getConflictID());

                    if (updatedSourceLocalItem != null) {
                        workspace.getWorkspaceWatcher().removeSkippedItem(updatedSourceLocalItem);

                        conflict.setSourceLocalItem(updatedSourceLocalItem);
                    }
                }

                throw new VersionControlException(e);
            }

            /* Process the resolved conflicts */
            final UpdateLocalVersionQueue ulvq = new UpdateLocalVersionQueue(workspace);

            try {
                for (final ResolveConflictHandler.UpdateLocalVersionSpec ulvSpec : handler
                        .getUpdateLocalVersionSpecs()) {
                    ulvq.queueUpdate(ulvSpec.getSourceServerItem(), ulvSpec.getItemID(),
                            ulvSpec.getSourceLocalItem(), ulvSpec.getVersionServer(),
                            ulvSpec.getProperyValues());
                }
            } finally {
                ulvq.close();
            }

            final GetEngine getEngine = new GetEngine(this);

            for (final ResolveConflictHandler.GetOperationGroup group : handler.getGetOpGroups()) {
                getEngine.processGetOperations(workspace, ProcessType.UNDO, group.getUndoOps(), GetOptions.NONE,
                        handler.getFlags());

                getEngine.processGetOperations(workspace, ProcessType.GET, group.getGetOps(), GetOptions.NONE,
                        handler.getFlags());
            }

            allResolvedConflicts.addAll(handler.getResolvedConflicts());
            flags = flags.combine(handler.getFlags());
        }

        finally {
            if (lock != null) {
                lock.close();
            }
        }
    }

    resolvedConflicts.set(allResolvedConflicts.toArray(new Conflict[allResolvedConflicts.size()]));

    if (flags.contains(ChangePendedFlags.WORKING_FOLDER_MAPPINGS_UPDATED)) {
        workspace.invalidateMappings();
    }
}

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

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

    if (bSave) {//  w w w.j a  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(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:com.jivesoftware.os.upena.deployable.UpenaMain.java

public void run(String[] args) throws Exception {

    HealthFactory.initialize(BindInterfaceToConfiguration::bindDefault, new HealthCheckRegistry() {

        @Override//from w  w w .j av  a2s.  co m
        public void register(HealthChecker<?> healthChecker) {

        }

        @Override
        public void unregister(HealthChecker<?> healthChecker) {

        }
    });

    Properties buildProperties = new Properties();
    String upenaVersion = "";
    try {
        buildProperties.load(UpenaMain.class.getClassLoader().getResourceAsStream("build.properties"));
        upenaVersion = buildProperties.getProperty("my.version", "") + " "
                + buildProperties.getProperty("my.timestamp", "") + " sha:"
                + buildProperties.getProperty("git.commit.id", "");
    } catch (Exception x) {
        LOG.warn("Failed to locate build.properties");
    }

    String workingDir = System.getProperty("user.dir");
    long start = System.currentTimeMillis();
    Exception failed = null;
    while (start + TimeUnit.SECONDS.toMillis(10) > System.currentTimeMillis()) {
        try {
            File lockFile = new File(workingDir, "onlyLetOneRunningAtATime");
            lockFile.createNewFile();
            FileChannel.open(lockFile.toPath(), StandardOpenOption.WRITE).lock();
            failed = null;
            break;
        } catch (Exception x) {
            failed = x;
            LOG.warn("Failed to acquire lock on onlyLetOneRunningAtATime", x);
            Thread.sleep(1000);
        }
    }
    if (failed != null) {
        throw failed;
    }

    JDIAPI jvmapi = null;
    try {
        jvmapi = new JDIAPI();
    } catch (NoClassDefFoundError x) {
        LOG.warn(
                "Failed to local tools.jar. Please manually add to classpath. Breakpoint debugger will be disabled.");
    }

    String hostname = args[0];

    int loopbackPort = Integer.parseInt(System.getProperty("amza.loopback.port", "1174"));
    int port = Integer.parseInt(System.getProperty("amza.port", "1175"));
    String multicastGroup = System.getProperty("amza.discovery.group", "225.4.5.6");
    int multicastPort = Integer.parseInt(System.getProperty("amza.discovery.port", "1123"));
    String clusterDiscoveryName = (args.length > 1 ? args[1] : null);

    String datacenter = System.getProperty("host.datacenter", "unknownDatacenter");
    String rack = System.getProperty("host.rack", "unknownRack");
    String publicHost = System.getProperty("public.host.name", hostname);

    UpenaRingHost ringHost = new UpenaRingHost(hostname, port); // TODO include rackId

    // todo need a better way to create writer id.
    int writerId = new Random().nextInt(512);
    TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(
            new ConstantWriterIdProvider(writerId));

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    RowsStorageProvider rowsStorageProvider = rowsStorageProvider(orderIdProvider);

    boolean sslEnable = Boolean.parseBoolean(System.getProperty("ssl.enabled", "true"));
    String sslKeystorePassword = System.getProperty("ssl.keystore.password", "password");
    String sslKeystorePath = System.getProperty("ssl.keystore.path", "./certs/sslKeystore");
    String sslKeyStoreAlias = System.getProperty("ssl.keystore.alias", "upenanode").toLowerCase();
    boolean sslAutoGenerateSelfSignedCert = Boolean
            .parseBoolean(System.getProperty("ssl.keystore.autoGenerate", "true"));

    File sslKeystore = new File(sslKeystorePath);
    if (sslEnable) {
        SelfSigningCertGenerator selfSigningCertGenerator = new SelfSigningCertGenerator();
        if (sslKeystore.exists()) {
            if (!selfSigningCertGenerator.validate(sslKeyStoreAlias, sslKeystorePassword, sslKeystore)) {
                LOG.error("SSL keystore validation failed. keyStoreAlias:{} sslKeystore:{}", sslKeyStoreAlias,
                        sslKeystore);
                System.exit(1);
            }
        } else {
            sslKeystore.getParentFile().mkdirs();
            if (sslAutoGenerateSelfSignedCert) {
                selfSigningCertGenerator.create(sslKeyStoreAlias, sslKeystorePassword, sslKeystore);
            } else {
                LOG.error("Failed to locate mandatory sslKeystore:{}", sslKeystore);
                System.exit(1);
            }
        }
    }

    String consumerKey = System.getProperty("upena.consumerKey", clusterDiscoveryName);
    if (consumerKey == null) {
        consumerKey = "upena";
        LOG.warn("Please provide a stronger consumerKey via -Dupena.consumerKey");
    }
    String finalConsumerKey = consumerKey;

    String secret = System.getProperty("upena.secret");
    if (secret == null) {
        secret = "secret";
        LOG.warn("Please provide a stronger secret via -Dupena.secret");
    }
    String finalSecret = secret;

    OAuthSigner authSigner = (request) -> {
        CommonsHttpOAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(finalConsumerKey, finalSecret);
        oAuthConsumer.setMessageSigner(new HmacSha1MessageSigner());
        oAuthConsumer.setTokenWithSecret(finalConsumerKey, finalSecret);
        return oAuthConsumer.sign(request);
    };
    UpenaSSLConfig upenaSSLConfig = new UpenaSSLConfig(sslEnable, sslAutoGenerateSelfSignedCert, authSigner);

    UpenaAmzaService upenaAmzaService = null;
    if (!new File("./state").exists()) {
        UpdatesSender changeSetSender = new HttpUpdatesSender(sslEnable, sslAutoGenerateSelfSignedCert,
                authSigner);
        UpdatesTaker tableTaker = new HttpUpdatesTaker(sslEnable, sslAutoGenerateSelfSignedCert, authSigner);

        UpenaAmzaServiceConfig upenaAmzaServiceConfig = new UpenaAmzaServiceConfig();
        upenaAmzaService = new UpenaAmzaServiceInitializer().initialize(upenaAmzaServiceConfig, orderIdProvider,
                new com.jivesoftware.os.upena.amza.storage.FstMarshaller(
                        FSTConfiguration.getDefaultConfiguration()),
                rowsStorageProvider, rowsStorageProvider, rowsStorageProvider, changeSetSender, tableTaker,
                Optional.<SendFailureListener>absent(), Optional.<UpenaTakeFailureListener>absent(),
                (changes) -> {
                });

        /*upenaAmzaService.start(ringHost, upenaAmzaServiceConfig.resendReplicasIntervalInMillis,
            upenaAmzaServiceConfig.applyReplicasIntervalInMillis,
            upenaAmzaServiceConfig.takeFromNeighborsIntervalInMillis,
            upenaAmzaServiceConfig.checkIfCompactionIsNeededIntervalInMillis,
            upenaAmzaServiceConfig.compactTombstoneIfOlderThanNMillis);*/

        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      OLD Amza Service Online");
        LOG.info("-----------------------------------------------------------------------");
    } else {
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      OLD Amza Data is decomissionable");
        LOG.info("-----------------------------------------------------------------------");
    }

    BAInterner baInterner = new BAInterner();

    AtomicReference<Callable<RingTopology>> topologyProvider = new AtomicReference<>(); // bit of a hack
    InstanceDescriptor instanceDescriptor = new InstanceDescriptor(datacenter, rack, "", "", "", "", "", "", "",
            "", 0, "", "", "", 0L, true);
    ConnectionDescriptorsProvider noAuthConnectionsProvider = (connectionDescriptorsRequest,
            expectedReleaseGroup) -> {
        try {
            RingTopology systemRing = topologyProvider.get().call();
            List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries,
                    input -> new ConnectionDescriptor(instanceDescriptor, sslEnable, false,
                            new HostPort(input.ringHost.getHost(), input.ringHost.getPort()),
                            Collections.emptyMap(), Collections.emptyMap())));
            return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors,
                    connectionDescriptorsRequest.getRequestUuid());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };

    TenantsServiceConnectionDescriptorProvider<String> noAuthConnectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>(
            Executors.newScheduledThreadPool(1), "", noAuthConnectionsProvider, "", "", 10_000); // TODO config
    noAuthConnectionPoolProvider.start();

    ConnectionDescriptorsProvider connectionsProvider = (connectionDescriptorsRequest,
            expectedReleaseGroup) -> {
        try {
            RingTopology systemRing = topologyProvider.get().call();
            List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries,
                    input -> new ConnectionDescriptor(instanceDescriptor, sslEnable, true,
                            new HostPort(input.ringHost.getHost(), input.ringHost.getPort()),
                            Collections.emptyMap(), Collections.emptyMap())));
            return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors,
                    connectionDescriptorsRequest.getRequestUuid());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };

    TenantsServiceConnectionDescriptorProvider<String> connectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>(
            Executors.newScheduledThreadPool(1), "", connectionsProvider, "", "", 10_000); // TODO config
    connectionPoolProvider.start();

    HttpDeliveryClientHealthProvider clientHealthProvider = new HttpDeliveryClientHealthProvider("", null, "",
            5000, 100);

    TenantRoutingHttpClientInitializer<String> nonSigningClientInitializer = new TenantRoutingHttpClientInitializer<>(
            null);

    TenantAwareHttpClient<String> systemTakeClient = nonSigningClientInitializer
            .builder(noAuthConnectionPoolProvider, // TODO config
                    clientHealthProvider)
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); // TODO expose to conf
    TenantAwareHttpClient<String> stripedTakeClient = nonSigningClientInitializer
            .builder(noAuthConnectionPoolProvider, // TODO config
                    clientHealthProvider)
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); // TODO expose to conf

    TenantRoutingHttpClientInitializer<String> tenantRoutingHttpClientInitializer = new TenantRoutingHttpClientInitializer<>(
            new OAuthSignerProvider(() -> authSigner));

    TenantAwareHttpClient<String> ringClient = tenantRoutingHttpClientInitializer
            .builder(connectionPoolProvider, // TODO config
                    clientHealthProvider)
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); // TODO expose to conf
    AmzaStats amzaStats = new AmzaStats();

    AmzaService amzaService = startAmza(workingDir, amzaStats, baInterner, writerId,
            new RingHost(datacenter, rack, ringHost.getHost(), ringHost.getPort()),
            new RingMember(ringHost.getHost() + ":" + ringHost.getPort()), authSigner, systemTakeClient,
            stripedTakeClient, ringClient, topologyProvider, clusterDiscoveryName, multicastGroup,
            multicastPort);

    EmbeddedClientProvider embeddedClientProvider = new EmbeddedClientProvider(amzaService);

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Amza Service Online");
    LOG.info("-----------------------------------------------------------------------");

    ObjectMapper storeMapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    UpenaConfigStore upenaConfigStore = new UpenaConfigStore(orderIdProvider, storeMapper, upenaAmzaService,
            amzaService, embeddedClientProvider);

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Upena Config Store Online");
    LOG.info("-----------------------------------------------------------------------");

    ExecutorService instanceChangedThreads = Executors.newFixedThreadPool(32);

    AtomicReference<UbaService> ubaServiceReference = new AtomicReference<>();
    UpenaStore upenaStore = new UpenaStore(storeMapper, upenaAmzaService, (instanceChanges) -> {
        instanceChangedThreads.submit(() -> {
            UbaService got = ubaServiceReference.get();
            if (got != null) {
                try {
                    got.instanceChanged(instanceChanges);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }, (changes) -> {
    }, (change) -> {
        LOG.info("TODO: tie into conductor. " + change);
    }, amzaService, embeddedClientProvider);
    //upenaStore.attachWatchers();

    ChaosService chaosService = new ChaosService(upenaStore);
    SecureRandom random = new SecureRandom();
    PasswordStore passwordStore = (key) -> {
        String password = System.getProperty("sauth.keystore.password");
        if (password == null) {
            File passwordFile = new File(workingDir, "keystore/" + key + ".key");
            if (passwordFile.exists()) {
                password = Files.toString(passwordFile, StandardCharsets.UTF_8);
            } else {
                passwordFile.getParentFile().mkdirs();
                password = new BigInteger(130, random).toString(32);
                Files.write(password, passwordFile, StandardCharsets.UTF_8);
            }
        }
        return password;
    };

    SessionStore sessionStore = new SessionStore(TimeUnit.MINUTES.toMillis(60), TimeUnit.MINUTES.toMillis(30));

    AtomicReference<UpenaHealth> upenaHealthProvider = new AtomicReference<>();
    InstanceHealthly instanceHealthly = (key, version) -> {
        UpenaHealth upenaHealth = upenaHealthProvider.get();
        if (upenaHealth == null) {
            return false;
        }
        ConcurrentMap<RingHost, NodeHealth> ringHostNodeHealth = upenaHealth.buildClusterHealth();
        for (NodeHealth nodeHealth : ringHostNodeHealth.values()) {
            for (NannyHealth nannyHealth : nodeHealth.nannyHealths) {
                if (nannyHealth.instanceDescriptor.instanceKey.equals(key.getKey())) {
                    return nannyHealth.serviceHealth.fullyOnline
                            ? nannyHealth.serviceHealth.version.equals(version)
                            : false;
                }
            }
        }
        return false;
    };
    UpenaService upenaService = new UpenaService(passwordStore, sessionStore, upenaStore, chaosService,
            instanceHealthly);

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Upena Service Online");
    LOG.info("-----------------------------------------------------------------------");

    File defaultPathToRepo = new File(new File(System.getProperty("user.dir"), ".m2"), "repository");
    PathToRepo localPathToRepo = new PathToRepo(
            new File(System.getProperty("pathToRepo", defaultPathToRepo.getAbsolutePath())));
    RepositoryProvider repositoryProvider = new RepositoryProvider(localPathToRepo);

    Host host = new Host(publicHost, datacenter, rack, ringHost.getHost(), ringHost.getPort(), workingDir, null,
            null);
    HostKey hostKey = new HostKeyProvider().getNodeKey(upenaStore.hosts, host);

    String hostInstanceId = System.getProperty("host.instance.id", hostKey.getKey());
    host = new Host(publicHost, datacenter, rack, ringHost.getHost(), ringHost.getPort(), workingDir,
            hostInstanceId, null);

    UbaLog ubaLog = (what, why, how) -> {
        try {
            upenaStore.record("Uba", what, System.currentTimeMillis(), why,
                    ringHost.getHost() + ":" + ringHost.getPort(), how);
        } catch (Exception x) {
            x.printStackTrace(); // Hmm lame
        }
    };

    OktaLog oktaLog = (who, what, why, how) -> {
        try {
            upenaStore.record("okta:" + who, what, System.currentTimeMillis(), why,
                    ringHost.getHost() + ":" + ringHost.getPort(), how);
        } catch (Exception x) {
            x.printStackTrace(); // Hmm lame
        }
    };

    OktaCredentialsMatcher.oktaLog = oktaLog;
    OktaRealm.oktaLog = oktaLog;

    UpenaClient upenaClient = new UpenaClient() {
        @Override
        public InstanceDescriptorsResponse instanceDescriptor(
                InstanceDescriptorsRequest instanceDescriptorsRequest) throws Exception {
            return upenaService.instanceDescriptors(instanceDescriptorsRequest);
        }

        @Override
        public void updateKeyPair(String instanceKey, String publicKey) throws Exception {
            Instance i = upenaStore.instances.get(new InstanceKey(instanceKey));
            if (i != null) {
                LOG.info("Updating publicKey for {}", instanceKey);
                upenaStore.instances.update(new InstanceKey(instanceKey),
                        new Instance(i.clusterKey, i.hostKey, i.serviceKey, i.releaseGroupKey, i.instanceId,
                                i.enabled, i.locked, publicKey, i.restartTimestampGMTMillis, i.ports));
            }
        }

    };

    final UbaService ubaService = new UbaServiceInitializer().initialize(passwordStore, upenaClient,
            repositoryProvider, hostKey.getKey(), workingDir,
            new UbaCoordinate(datacenter, rack, publicHost, host.hostName, "localhost", loopbackPort), null,
            ubaLog);

    UpenaHealth upenaHealth = new UpenaHealth(amzaService, upenaSSLConfig, upenaConfigStore, ubaService,
            new RingHost(datacenter, rack, ringHost.getHost(), ringHost.getPort()), hostKey);
    upenaHealthProvider.set(upenaHealth);

    DiscoveredRoutes discoveredRoutes = new DiscoveredRoutes();
    ShiroRequestHelper shiroRequestHelper = new ShiroRequestHelper(TimeUnit.DAYS.toMillis(1)); // TODO expose Sys prop?

    String shiroConfigLocation = System.getProperty("shiro.ini.location", "classpath:shiro.ini"); // classpath:oktashiro.ini

    UpenaJerseyEndpoints jerseyEndpoints = new UpenaJerseyEndpoints(shiroConfigLocation)
            .addInjectable(ShiroRequestHelper.class, shiroRequestHelper)
            .addEndpoint(UpenaClusterRestEndpoints.class).addEndpoint(UpenaHostRestEndpoints.class)
            .addEndpoint(UpenaServiceRestEndpoints.class).addEndpoint(UpenaReleaseRestEndpoints.class)
            .addEndpoint(UpenaInstanceRestEndpoints.class).addEndpoint(UpenaTenantRestEndpoints.class)
            .addInjectable(upenaHealth).addInjectable(upenaService).addInjectable(upenaStore)
            .addInjectable(upenaConfigStore).addInjectable(ubaService)
            //.addEndpoint(AmzaReplicationRestEndpoints.class)
            //.addInjectable(UpenaAmzaInstance.class, upenaAmzaService)
            .addEndpoint(UpenaEndpoints.class).addEndpoint(UpenaConnectivityEndpoints.class)
            .addEndpoint(UpenaManagedDeployableEndpoints.class).addEndpoint(UpenaHealthEndpoints.class)
            .addEndpoint(UpenaRepoEndpoints.class).addInjectable(DiscoveredRoutes.class, discoveredRoutes)
            .addInjectable(UpenaRingHost.class, ringHost).addInjectable(HostKey.class, hostKey)
            .addInjectable(UpenaAutoRelease.class, new UpenaAutoRelease(repositoryProvider, upenaStore))
            .addInjectable(PathToRepo.class, localPathToRepo);

    PercentileHealthCheckConfig phcc = bindDefault(PercentileHealthCheckConfig.class);
    PercentileHealthChecker authFilterHealthCheck = new PercentileHealthChecker(phcc);
    AuthValidationFilter authValidationFilter = new AuthValidationFilter(authFilterHealthCheck);
    authValidationFilter.addEvaluator(new NoAuthEvaluator(), "/", "/swagger.json", "/ui/*", // Handled by Shiro
            "/repo/*" // Cough
    );

    OAuth1Signature verifier = new OAuth1Signature(new OAuthServiceLocatorShim());
    OAuthSecretManager oAuthSecretManager = new OAuthSecretManager() {
        @Override
        public void clearCache() {
        }

        @Override
        public String getSecret(String id) throws AuthValidationException {
            return id.equals(finalConsumerKey) ? finalSecret : null;
        }

        @Override
        public void verifyLastSecretRemovalTime() throws Exception {
        }
    };
    AuthValidator<OAuth1Signature, OAuth1Request> oAuthValidator = new DefaultOAuthValidator(
            Executors.newScheduledThreadPool(1), Long.MAX_VALUE, oAuthSecretManager, 60_000, false, false);
    oAuthValidator.start();
    authValidationFilter.addEvaluator(new NoAuthEvaluator(), "/repo/*", "/amza/rows/stream/*",
            "/amza/rows/taken/*", "/amza/pong/*", "/amza/invalidate/*");
    authValidationFilter.addEvaluator(new OAuthEvaluator(oAuthValidator, verifier), "/upena/*", "/amza/*");

    // TODO something better someday
    String upenaApiUsername = System.getProperty("upena.api.username", null);
    String upenaApiPassword = System.getProperty("upena.api.password", null);

    if (upenaApiUsername != null && upenaApiPassword != null) {
        authValidationFilter.addEvaluator(containerRequestContext -> {
            String authCredentials = containerRequestContext.getHeaderString("Authorization");
            if (authCredentials == null) {
                return AuthStatus.not_handled;
            }

            final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
            String usernameAndPassword = null;
            try {
                byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
                usernameAndPassword = new String(decodedBytes, "UTF-8");
            } catch (IOException e) {
                return AuthStatus.denied;
            }
            final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
            final String username = tokenizer.nextToken();
            final String password = tokenizer.nextToken();

            boolean authenticationStatus = upenaApiUsername.equals(username)
                    && upenaApiPassword.equals(password);

            return authenticationStatus ? AuthStatus.authorized : AuthStatus.denied;
        }, "/api/*");
    }

    jerseyEndpoints.addContainerRequestFilter(authValidationFilter);

    String region = System.getProperty("aws.region", null);
    String roleArn = System.getProperty("aws.roleArn", null);

    AWSClientFactory awsClientFactory = new AWSClientFactory(region, roleArn);

    String accountName = System.getProperty("account.name",
            clusterDiscoveryName == null ? "" : clusterDiscoveryName);
    String humanReadableUpenaClusterName = datacenter + " - " + accountName;
    injectUI(upenaVersion, awsClientFactory, storeMapper, mapper, jvmapi, amzaService, localPathToRepo,
            repositoryProvider, hostKey, ringHost, upenaSSLConfig, port, sessionStore, ubaService, upenaHealth,
            upenaStore, upenaConfigStore, jerseyEndpoints, humanReadableUpenaClusterName, discoveredRoutes);

    injectAmza(baInterner, amzaStats, jerseyEndpoints, amzaService, ringClient);

    InitializeRestfulServer initializeRestfulServer = new InitializeRestfulServer(false, port, "UpenaNode",
            sslEnable, sslKeyStoreAlias, sslKeystorePassword, sslKeystorePath, 128, 10_000);

    buildSwagger();
    initializeRestfulServer.addClasspathResource("/resources");
    initializeRestfulServer.addContextHandler("/", jerseyEndpoints);

    RestfulServer restfulServer = initializeRestfulServer.build();
    restfulServer.start();

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Jetty Service Online");
    LOG.info("-----------------------------------------------------------------------");

    UpenaJerseyEndpoints loopbackJerseyEndpoints = new UpenaJerseyEndpoints(null)
            .addEndpoint(UpenaLoopbackEndpoints.class).addEndpoint(UpenaConfigRestEndpoints.class)
            .addInjectable(SessionStore.class, sessionStore)
            .addInjectable(DiscoveredRoutes.class, discoveredRoutes).addInjectable(upenaConfigStore)
            .addInjectable(upenaStore).addInjectable(upenaHealth)
            .addInjectable(UpenaService.class, upenaService);

    InitializeRestfulServer initializeLoopbackRestfulServer = new InitializeRestfulServer(
            Boolean.parseBoolean(System.getProperty("amza.loopback.strict", "true")), loopbackPort, "UpenaNode",
            false, sslKeyStoreAlias, sslKeystorePassword, sslKeystorePath, 128, 10_000);
    initializeLoopbackRestfulServer.addClasspathResource("/resources");
    initializeLoopbackRestfulServer.addContextHandler("/", loopbackJerseyEndpoints);

    RestfulServer loopbackRestfulServer = initializeLoopbackRestfulServer.build();
    loopbackRestfulServer.start();

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Jetty Service Online");
    LOG.info("-----------------------------------------------------------------------");

    if (ubaService != null) {
        Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> {
            try {
                ubaService.nanny();
            } catch (Exception ex) {
                LOG.error("Nanny failure", ex);
            }
        }, 15, 15, TimeUnit.SECONDS);
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      Uba Service Online");
        LOG.info("-----------------------------------------------------------------------");
    }
    ubaServiceReference.set(ubaService);

    /*String peers = System.getProperty("manual.peers");
    if (peers != null) {
    String[] hostPortTuples = peers.split(",");
    for (String hostPortTuple : hostPortTuples) {
        String hostPort = hostPortTuple.trim();
        if (hostPort.length() > 0 && hostPort.contains(":")) {
            String[] host_port = hostPort.split(":");
            try {
                UpenaRingHost anotherRingHost = new UpenaRingHost(host_port[0].trim(), Integer.parseInt(host_port[1].trim()));
                List<UpenaRingHost> ring = upenaAmzaService.getRing("master");
                if (!ring.contains(anotherRingHost)) {
                    LOG.info("Adding host to the cluster: " + anotherRingHost);
                    upenaAmzaService.addRingHost("master", anotherRingHost);
                }
            } catch (Exception x) {
                LOG.warn("Malformed hostPortTuple {}", hostPort);
            }
        } else {
            LOG.warn("Malformed hostPortTuple {}", hostPort);
        }
    }
    }*/

    String vpc = System.getProperty("aws.vpc", null);
    UpenaAWSLoadBalancerNanny upenaAWSLoadBalancerNanny = new UpenaAWSLoadBalancerNanny(vpc, upenaStore,
            hostKey, awsClientFactory);

    Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> {
        try {
            upenaAWSLoadBalancerNanny.ensureSelf();
        } catch (Exception x) {
            LOG.warn("Failures while nannying load loadbalancer.", x);
        }
    }, 1, 1, TimeUnit.MINUTES); // TODO better

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|     Waiting for amza to be ready....");
    LOG.info("-----------------------------------------------------------------------");
    while (!amzaService.isReady()) {
        Thread.sleep(1000);
    }

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|     Begin Migration");
    LOG.info("-----------------------------------------------------------------------");

    upenaStore.init(orderIdProvider, Integer.parseInt(System.getProperty("min.service.port", "10000")),
            Integer.parseInt(System.getProperty("max.service.port", String.valueOf(Short.MAX_VALUE))), false);

    upenaConfigStore.init();

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|     End Migration");
    LOG.info("-----------------------------------------------------------------------");

    addManualPeers(amzaService);

    Host gotHost = upenaStore.hosts.get(hostKey);
    if (gotHost == null || !gotHost.equals(host)) {
        upenaStore.hosts.update(hostKey, host);
    }
}

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

private QueryTripsResult queryTripsBinary(final HttpUrl url, final Location from, final @Nullable Location via,
        final Location to, final int expectedBufferSize) throws IOException {
    /*/*from  w  w  w .j  a v  a2s  .c o  m*/
     * Many thanks to Malte Starostik and Robert, who helped a lot with analyzing this API!
     */

    final AtomicReference<QueryTripsResult> result = new AtomicReference<>();

    httpClient.getInputStream(new HttpClient.Callback() {
        @Override
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            final CustomBufferedInputStream bis = new CustomBufferedInputStream(
                    new GZIPInputStream(body.byteStream()));

            // initialize input stream
            final LittleEndianDataInputStream is = new LittleEndianDataInputStream(bis);
            is.mark(expectedBufferSize);

            // quick check of status
            final int version = is.readShortReverse();
            if (version != 6 && version != 5)
                throw new IllegalStateException("unknown version: " + version + ", first chars: " + bodyPeek);
            final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT, Integer.toString(version),
                    null, 0, null);

            // quick seek for pointers
            is.reset();
            is.skipBytes(0x20);
            final int serviceDaysTablePtr = is.readIntReverse();
            final int stringTablePtr = is.readIntReverse();

            is.reset();
            is.skipBytes(0x36);
            final int stationTablePtr = is.readIntReverse();
            final int commentTablePtr = is.readIntReverse();

            is.reset();
            is.skipBytes(0x46);
            final int extensionHeaderPtr = is.readIntReverse();

            // read strings
            final StringTable strings = new StringTable(is, stringTablePtr,
                    serviceDaysTablePtr - stringTablePtr);

            is.reset();
            is.skipBytes(extensionHeaderPtr);

            // read extension header
            final int extensionHeaderLength = is.readIntReverse();
            if (extensionHeaderLength < 0x2c)
                throw new IllegalStateException("too short: " + extensionHeaderLength);

            is.skipBytes(12);
            final int errorCode = is.readShortReverse();

            if (errorCode == 0) {
                // string encoding
                is.skipBytes(14);
                final Charset stringEncoding = Charset.forName(strings.read(is));
                strings.setEncoding(stringEncoding);

                // read number of trips
                is.reset();
                is.skipBytes(30);

                final int numTrips = is.readShortReverse();
                if (numTrips == 0) {
                    result.set(new QueryTripsResult(header, url.toString(), from, via, to, null,
                            new LinkedList<Trip>()));
                    return;
                }

                // read rest of header
                is.reset();
                is.skipBytes(0x02);

                final Location resDeparture = location(is, strings);
                final Location resArrival = location(is, strings);

                is.skipBytes(10);

                final long resDate = date(is);
                /* final long resDate30 = */date(is);

                is.reset();
                is.skipBytes(extensionHeaderPtr + 0x8);

                final int seqNr = is.readShortReverse();
                if (seqNr == 0)
                    throw new SessionExpiredException();
                else if (seqNr < 0)
                    throw new IllegalStateException("illegal sequence number: " + seqNr);

                final String requestId = strings.read(is);

                final int tripDetailsPtr = is.readIntReverse();
                if (tripDetailsPtr == 0)
                    throw new IllegalStateException("no connection details");

                is.skipBytes(4);

                final int disruptionsPtr = is.readIntReverse();

                is.skipBytes(10);

                final String ld = strings.read(is);
                final int attrsOffset = is.readIntReverse();

                final int tripAttrsPtr;
                if (extensionHeaderLength >= 0x30) {
                    if (extensionHeaderLength < 0x32)
                        throw new IllegalArgumentException("too short: " + extensionHeaderLength);
                    is.reset();
                    is.skipBytes(extensionHeaderPtr + 0x2c);
                    tripAttrsPtr = is.readIntReverse();
                } else {
                    tripAttrsPtr = 0;
                }

                // determine stops offset
                is.reset();
                is.skipBytes(tripDetailsPtr);
                final int tripDetailsVersion = is.readShortReverse();
                if (tripDetailsVersion != 1)
                    throw new IllegalStateException("unknown trip details version: " + tripDetailsVersion);
                is.skipBytes(0x02);

                final int tripDetailsIndexOffset = is.readShortReverse();
                final int tripDetailsLegOffset = is.readShortReverse();
                final int tripDetailsLegSize = is.readShortReverse();
                final int stopsSize = is.readShortReverse();
                final int stopsOffset = is.readShortReverse();

                // read stations
                final StationTable stations = new StationTable(is, stationTablePtr,
                        commentTablePtr - stationTablePtr, strings);

                // read comments
                final CommentTable comments = new CommentTable(is, commentTablePtr,
                        tripDetailsPtr - commentTablePtr, strings);

                final List<Trip> trips = new ArrayList<>(numTrips);

                // read trips
                for (int iTrip = 0; iTrip < numTrips; iTrip++) {
                    is.reset();
                    is.skipBytes(0x4a + iTrip * 12);

                    final int serviceDaysTableOffset = is.readShortReverse();

                    final int legsOffset = is.readIntReverse();

                    final int numLegs = is.readShortReverse();

                    final int numChanges = is.readShortReverse();

                    /* final long duration = time(is, 0, 0); */is.readShortReverse();

                    is.reset();
                    is.skipBytes(serviceDaysTablePtr + serviceDaysTableOffset);

                    /* final String serviceDaysText = */strings.read(is);

                    final int serviceBitBase = is.readShortReverse();
                    final int serviceBitLength = is.readShortReverse();

                    int tripDayOffset = serviceBitBase * 8;
                    for (int i = 0; i < serviceBitLength; i++) {
                        int serviceBits = is.read();
                        if (serviceBits == 0) {
                            tripDayOffset += 8;
                            continue;
                        }
                        while ((serviceBits & 0x80) == 0) {
                            serviceBits = serviceBits << 1;
                            tripDayOffset++;
                        }
                        break;
                    }

                    is.reset();
                    is.skipBytes(tripDetailsPtr + tripDetailsIndexOffset + iTrip * 2);
                    final int tripDetailsOffset = is.readShortReverse();

                    is.reset();
                    is.skipBytes(tripDetailsPtr + tripDetailsOffset);
                    final int realtimeStatus = is.readShortReverse();

                    /* final short delay = */is.readShortReverse();

                    /* final int legIndex = */is.readShortReverse();

                    is.skipBytes(2); // 0xffff

                    /* final int legStatus = */is.readShortReverse();

                    is.skipBytes(2); // 0x0000

                    String connectionId = null;
                    if (tripAttrsPtr != 0) {
                        is.reset();
                        is.skipBytes(tripAttrsPtr + iTrip * 2);
                        final int tripAttrsIndex = is.readShortReverse();

                        is.reset();
                        is.skipBytes(attrsOffset + tripAttrsIndex * 4);
                        while (true) {
                            final String key = strings.read(is);
                            if (key == null)
                                break;
                            else if (key.equals("ConnectionId"))
                                connectionId = strings.read(is);
                            else
                                is.skipBytes(2);
                        }
                    }

                    final List<Trip.Leg> legs = new ArrayList<>(numLegs);

                    for (int iLegs = 0; iLegs < numLegs; iLegs++) {
                        is.reset();
                        is.skipBytes(0x4a + legsOffset + iLegs * 20);

                        final long plannedDepartureTime = time(is, resDate, tripDayOffset);
                        final Location departureLocation = stations.read(is);

                        final long plannedArrivalTime = time(is, resDate, tripDayOffset);
                        final Location arrivalLocation = stations.read(is);

                        final int type = is.readShortReverse();

                        final String lineName = strings.read(is);

                        final Position plannedDeparturePosition = normalizePosition(strings.read(is));
                        final Position plannedArrivalPosition = normalizePosition(strings.read(is));

                        final int legAttrIndex = is.readShortReverse();

                        final List<Line.Attr> lineAttrs = new ArrayList<>();
                        String lineComment = null;
                        boolean lineOnDemand = false;
                        for (final String comment : comments.read(is)) {
                            if (comment.startsWith("bf ")) {
                                lineAttrs.add(Line.Attr.WHEEL_CHAIR_ACCESS);
                            } else if (comment.startsWith("FA ") || comment.startsWith("FB ")
                                    || comment.startsWith("FR ")) {
                                lineAttrs.add(Line.Attr.BICYCLE_CARRIAGE);
                            } else if (comment.startsWith("$R ") || comment.startsWith("ga ")
                                    || comment.startsWith("ja ") || comment.startsWith("Vs ")
                                    || comment.startsWith("mu ") || comment.startsWith("mx ")) {
                                lineOnDemand = true;
                                lineComment = comment.substring(5);
                            }
                        }

                        is.reset();
                        is.skipBytes(attrsOffset + legAttrIndex * 4);
                        String directionStr = null;
                        int lineClass = 0;
                        String lineCategory = null;
                        String routingType = null;
                        String lineNetwork = null;
                        while (true) {
                            final String key = strings.read(is);
                            if (key == null)
                                break;
                            else if (key.equals("Direction"))
                                directionStr = strings.read(is);
                            else if (key.equals("Class"))
                                lineClass = Integer.parseInt(strings.read(is));
                            else if (key.equals("Category"))
                                lineCategory = strings.read(is);
                            // else if (key.equals("Operator"))
                            // lineOperator = strings.read(is);
                            else if (key.equals("GisRoutingType"))
                                routingType = strings.read(is);
                            else if (key.equals("AdminCode"))
                                lineNetwork = normalizeLineAdministration(strings.read(is));
                            else
                                is.skipBytes(2);
                        }

                        if (lineCategory == null && lineName != null)
                            lineCategory = categoryFromName(lineName);

                        is.reset();
                        is.skipBytes(tripDetailsPtr + tripDetailsOffset + tripDetailsLegOffset
                                + iLegs * tripDetailsLegSize);

                        if (tripDetailsLegSize != 16)
                            throw new IllegalStateException(
                                    "unhandled trip details leg size: " + tripDetailsLegSize);

                        final long predictedDepartureTime = time(is, resDate, tripDayOffset);
                        final long predictedArrivalTime = time(is, resDate, tripDayOffset);
                        final Position predictedDeparturePosition = normalizePosition(strings.read(is));
                        final Position predictedArrivalPosition = normalizePosition(strings.read(is));

                        final int bits = is.readShortReverse();
                        final boolean arrivalCancelled = (bits & 0x10) != 0;
                        final boolean departureCancelled = (bits & 0x20) != 0;

                        is.readShort();

                        final int firstStopIndex = is.readShortReverse();

                        final int numStops = is.readShortReverse();

                        is.reset();
                        is.skipBytes(disruptionsPtr);

                        String disruptionText = null;

                        if (is.readShortReverse() == 1) {
                            is.reset();
                            is.skipBytes(disruptionsPtr + 2 + iTrip * 2);

                            int disruptionsOffset = is.readShortReverse();
                            while (disruptionsOffset != 0) {
                                is.reset();
                                is.skipBytes(disruptionsPtr + disruptionsOffset);

                                strings.read(is); // "0"

                                final int disruptionLeg = is.readShortReverse();

                                is.skipBytes(2); // bitmaske

                                strings.read(is); // start of line
                                strings.read(is); // end of line

                                strings.read(is);
                                // id
                                /* final String disruptionTitle = */strings.read(is);
                                final String disruptionShortText = ParserUtils.formatHtml(strings.read(is));

                                disruptionsOffset = is.readShortReverse(); // next

                                if (iLegs == disruptionLeg) {
                                    final int disruptionAttrsIndex = is.readShortReverse();

                                    is.reset();
                                    is.skipBytes(attrsOffset + disruptionAttrsIndex * 4);

                                    while (true) {
                                        final String key = strings.read(is);
                                        if (key == null)
                                            break;
                                        else if (key.equals("Text"))
                                            disruptionText = ParserUtils.resolveEntities(strings.read(is));
                                        else
                                            is.skipBytes(2);
                                    }

                                    if (disruptionShortText != null)
                                        disruptionText = disruptionShortText;
                                }
                            }
                        }

                        List<Stop> intermediateStops = null;

                        if (numStops > 0) {
                            is.reset();
                            is.skipBytes(tripDetailsPtr + stopsOffset + firstStopIndex * stopsSize);

                            if (stopsSize != 26)
                                throw new IllegalStateException("unhandled stops size: " + stopsSize);

                            intermediateStops = new ArrayList<>(numStops);

                            for (int iStop = 0; iStop < numStops; iStop++) {
                                final long plannedStopDepartureTime = time(is, resDate, tripDayOffset);
                                final Date plannedStopDepartureDate = plannedStopDepartureTime != 0
                                        ? new Date(plannedStopDepartureTime)
                                        : null;
                                final long plannedStopArrivalTime = time(is, resDate, tripDayOffset);
                                final Date plannedStopArrivalDate = plannedStopArrivalTime != 0
                                        ? new Date(plannedStopArrivalTime)
                                        : null;
                                final Position plannedStopDeparturePosition = normalizePosition(
                                        strings.read(is));
                                final Position plannedStopArrivalPosition = normalizePosition(strings.read(is));

                                is.readInt();

                                final long predictedStopDepartureTime = time(is, resDate, tripDayOffset);
                                final Date predictedStopDepartureDate = predictedStopDepartureTime != 0
                                        ? new Date(predictedStopDepartureTime)
                                        : null;
                                final long predictedStopArrivalTime = time(is, resDate, tripDayOffset);
                                final Date predictedStopArrivalDate = predictedStopArrivalTime != 0
                                        ? new Date(predictedStopArrivalTime)
                                        : null;
                                final Position predictedStopDeparturePosition = normalizePosition(
                                        strings.read(is));
                                final Position predictedStopArrivalPosition = normalizePosition(
                                        strings.read(is));

                                final int stopBits = is.readShortReverse();
                                final boolean stopArrivalCancelled = (stopBits & 0x10) != 0;
                                final boolean stopDepartureCancelled = (stopBits & 0x20) != 0;

                                is.readShort();

                                final Location stopLocation = stations.read(is);

                                final boolean validPredictedDate = !dominantPlanStopTime
                                        || (plannedStopArrivalDate != null && plannedStopDepartureDate != null);

                                final Stop stop = new Stop(stopLocation, plannedStopArrivalDate,
                                        validPredictedDate ? predictedStopArrivalDate : null,
                                        plannedStopArrivalPosition, predictedStopArrivalPosition,
                                        stopArrivalCancelled, plannedStopDepartureDate,
                                        validPredictedDate ? predictedStopDepartureDate : null,
                                        plannedStopDeparturePosition, predictedStopDeparturePosition,
                                        stopDepartureCancelled);

                                intermediateStops.add(stop);
                            }
                        }

                        final Trip.Leg leg;
                        if (type == 1 /* Fussweg */ || type == 3 /* Uebergang */ || type == 4 /* Uebergang */) {
                            final Trip.Individual.Type individualType;
                            if (routingType == null)
                                individualType = type == 1 ? Trip.Individual.Type.WALK
                                        : Trip.Individual.Type.TRANSFER;
                            else if ("FOOT".equals(routingType))
                                individualType = Trip.Individual.Type.WALK;
                            else if ("BIKE".equals(routingType))
                                individualType = Trip.Individual.Type.BIKE;
                            else if ("CAR".equals(routingType) || "P+R".equals(routingType))
                                individualType = Trip.Individual.Type.CAR;
                            else
                                throw new IllegalStateException("unknown routingType: " + routingType);

                            final Date departureTime = new Date(
                                    predictedDepartureTime != 0 ? predictedDepartureTime
                                            : plannedDepartureTime);
                            final Date arrivalTime = new Date(
                                    predictedArrivalTime != 0 ? predictedArrivalTime : plannedArrivalTime);

                            final Trip.Leg lastLeg = legs.size() > 0 ? legs.get(legs.size() - 1) : null;
                            if (lastLeg != null && lastLeg instanceof Trip.Individual
                                    && ((Trip.Individual) lastLeg).type == individualType) {
                                final Trip.Individual lastIndividualLeg = (Trip.Individual) legs
                                        .remove(legs.size() - 1);
                                leg = new Trip.Individual(individualType, lastIndividualLeg.departure,
                                        lastIndividualLeg.departureTime, arrivalLocation, arrivalTime, null, 0);
                            } else {
                                leg = new Trip.Individual(individualType, departureLocation, departureTime,
                                        arrivalLocation, arrivalTime, null, 0);
                            }
                        } else if (type == 2) {
                            final Product lineProduct;
                            if (lineOnDemand)
                                lineProduct = Product.ON_DEMAND;
                            else if (lineClass != 0)
                                lineProduct = intToProduct(lineClass);
                            else
                                lineProduct = normalizeType(lineCategory);

                            final Line line = newLine(lineNetwork, lineProduct, normalizeLineName(lineName),
                                    lineComment, lineAttrs.toArray(new Line.Attr[0]));

                            final Location direction;
                            if (directionStr != null) {
                                final String[] directionPlaceAndName = splitStationName(directionStr);
                                direction = new Location(LocationType.ANY, null, directionPlaceAndName[0],
                                        directionPlaceAndName[1]);
                            } else {
                                direction = null;
                            }

                            final Stop departure = new Stop(departureLocation, true,
                                    plannedDepartureTime != 0 ? new Date(plannedDepartureTime) : null,
                                    predictedDepartureTime != 0 ? new Date(predictedDepartureTime) : null,
                                    plannedDeparturePosition, predictedDeparturePosition, departureCancelled);
                            final Stop arrival = new Stop(arrivalLocation, false,
                                    plannedArrivalTime != 0 ? new Date(plannedArrivalTime) : null,
                                    predictedArrivalTime != 0 ? new Date(predictedArrivalTime) : null,
                                    plannedArrivalPosition, predictedArrivalPosition, arrivalCancelled);

                            leg = new Trip.Public(line, direction, departure, arrival, intermediateStops, null,
                                    disruptionText);
                        } else {
                            throw new IllegalStateException("unhandled type: " + type);
                        }
                        legs.add(leg);
                    }

                    final Trip trip = new Trip(connectionId, resDeparture, resArrival, legs, null, null,
                            (int) numChanges);

                    if (realtimeStatus != 2) // Verbindung fllt aus
                        trips.add(trip);
                }

                // if result is only one single individual leg, don't query for more
                final boolean canQueryMore = trips.size() != 1 || trips.get(0).legs.size() != 1
                        || !(trips.get(0).legs.get(0) instanceof Trip.Individual);

                result.set(new QueryTripsResult(header, url.toString(), from, via, to,
                        new QueryTripsBinaryContext(requestId, seqNr, ld, bis.getCount(), canQueryMore),
                        trips));
            } else {
                log.debug("Hafas error: {}", errorCode);
                if (errorCode == 1) {
                    throw new SessionExpiredException();
                } else if (errorCode == 2) {
                    // F2: Your search results could not be stored internally.
                    throw new SessionExpiredException();
                } else if (errorCode == 8) {
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.AMBIGUOUS));
                    return;
                } else if (errorCode == 13) {
                    // IN13: Our booking system is currently being used by too many users at the same
                    // time.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else if (errorCode == 19) {
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else if (errorCode == 207) {
                    // H207: Unfortunately your connection request can currently not be processed.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else if (errorCode == 887) {
                    // H887: Your inquiry was too complex. Please try entering less intermediate stations.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 890) {
                    // H890: No connections have been found that correspond to your request. It is
                    // possible
                    // that the requested service does not operate from or to the places you stated on the
                    // requested date of travel.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 891) {
                    // H891: Unfortunately there was no route found. Missing timetable data could be the
                    // reason.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 892) {
                    // H892: Your inquiry was too complex. Please try entering less intermediate stations.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 899) {
                    // H899: there was an unsuccessful or incomplete search due to a timetable change.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 900) {
                    // Unsuccessful or incomplete search (timetable change)
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 9220) {
                    // H9220: Nearby to the given address stations could not be found.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNRESOLVABLE_ADDRESS));
                    return;
                } else if (errorCode == 9240) {
                    // H9240: Unfortunately there was no route found. Perhaps your start or destination is
                    // not
                    // served at all or with the selected means of transport on the required date/time.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 9260) {
                    // H9260: Unknown departure station
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNKNOWN_FROM));
                    return;
                } else if (errorCode == 9280) {
                    // H9280: Unknown intermediate station
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNKNOWN_VIA));
                    return;
                } else if (errorCode == 9300) {
                    // H9300: Unknown arrival station
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNKNOWN_TO));
                    return;
                } else if (errorCode == 9320) {
                    // The input is incorrect or incomplete
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.INVALID_DATE));
                    return;
                } else if (errorCode == 9360) {
                    // H9360: Unfortunately your connection request can currently not be processed.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.INVALID_DATE));
                    return;
                } else if (errorCode == 9380) {
                    // H9380: Dep./Arr./Intermed. or equivalent station defined more than once
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.TOO_CLOSE));
                    return;
                } else if (errorCode == 895) {
                    // H895: Departure/Arrival are too near
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.TOO_CLOSE));
                    return;
                } else if (errorCode == 65535) {
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else {
                    throw new IllegalStateException("error " + errorCode + " on " + url);
                }
            }
        }
    }, url);

    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/*from   ww w  .j a  v  a  2  s  . com*/
        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: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//from 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:org.apache.geode.management.internal.cli.commands.AlterRegionCommand.java

@CliCommand(value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
public Result alterRegion(
        @CliOption(key = CliStrings.ALTER_REGION__REGION, mandatory = true, help = CliStrings.ALTER_REGION__REGION__HELP) String regionPath,
        @CliOption(key = { CliStrings.GROUP,
                CliStrings.GROUPS }, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.ALTER_REGION__GROUP__HELP) String[] groups,
        @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
        @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
        @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
        @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
        @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
        @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
        @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
        @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
        @CliOption(key = CliStrings.ALTER_REGION__CACHELISTENER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHELISTENER__HELP) String[] cacheListeners,
        @CliOption(key = CliStrings.ALTER_REGION__CACHELOADER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHELOADER__HELP) String cacheLoader,
        @CliOption(key = CliStrings.ALTER_REGION__CACHEWRITER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHEWRITER__HELP) String cacheWriter,
        @CliOption(key = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
        @CliOption(key = CliStrings.ALTER_REGION__GATEWAYSENDERID, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
        @CliOption(key = CliStrings.ALTER_REGION__CLONINGENABLED, specifiedDefaultValue = "false", help = CliStrings.ALTER_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
        @CliOption(key = CliStrings.ALTER_REGION__EVICTIONMAX, specifiedDefaultValue = "0", help = CliStrings.ALTER_REGION__EVICTIONMAX__HELP) Integer evictionMax) {
    Result result;/*www. ja v  a 2  s. c  om*/
    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();

    getSecurityService().authorize(Resource.DATA, Operation.MANAGE, regionPath);

    try {
        InternalCache cache = getCache();

        if (groups != null) {
            RegionCommandsUtils.validateGroups(cache, groups);
        }

        RegionFunctionArgs.ExpirationAttrs entryIdle = null;
        if (entryExpirationIdleTime != null || entryExpirationIdleTimeAction != null) {
            if (entryExpirationIdleTime != null && entryExpirationIdleTime == -1) {
                entryExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
            }
            if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationIdleTimeAction)) {
                entryExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
            }
            entryIdle = new RegionFunctionArgs.ExpirationAttrs(
                    RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
                    entryExpirationIdleTimeAction);
        }
        RegionFunctionArgs.ExpirationAttrs entryTTL = null;
        if (entryExpirationTTL != null || entryExpirationTTLAction != null) {
            if (entryExpirationTTL != null && entryExpirationTTL == -1) {
                entryExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
            }
            if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationTTLAction)) {
                entryExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
            }
            entryTTL = new RegionFunctionArgs.ExpirationAttrs(
                    RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
                    entryExpirationTTLAction);
        }
        RegionFunctionArgs.ExpirationAttrs regionIdle = null;
        if (regionExpirationIdleTime != null || regionExpirationIdleTimeAction != null) {
            if (regionExpirationIdleTime != null && regionExpirationIdleTime == -1) {
                regionExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
            }
            if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationIdleTimeAction)) {
                regionExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
            }
            regionIdle = new RegionFunctionArgs.ExpirationAttrs(
                    RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
                    regionExpirationIdleTimeAction);
        }
        RegionFunctionArgs.ExpirationAttrs regionTTL = null;
        if (regionExpirationTTL != null || regionExpirationTTLAction != null) {
            if (regionExpirationTTL != null && regionExpirationTTL == -1) {
                regionExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
            }
            if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationTTLAction)) {
                regionExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
            }
            regionTTL = new RegionFunctionArgs.ExpirationAttrs(
                    RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
                    regionExpirationTTLAction);
        }

        cacheLoader = convertDefaultValue(cacheLoader, StringUtils.EMPTY);
        cacheWriter = convertDefaultValue(cacheWriter, StringUtils.EMPTY);

        RegionFunctionArgs regionFunctionArgs;
        regionFunctionArgs = new RegionFunctionArgs(regionPath, null, null, false, null, null, null, entryIdle,
                entryTTL, regionIdle, regionTTL, null, null, null, null, cacheListeners, cacheLoader,
                cacheWriter, asyncEventQueueIds, gatewaySenderIds, null, cloningEnabled, null, null, null, null,
                null, null, null, null, evictionMax, null, null, null, null);

        Set<String> cacheListenersSet = regionFunctionArgs.getCacheListeners();
        if (cacheListenersSet != null && !cacheListenersSet.isEmpty()) {
            for (String cacheListener : cacheListenersSet) {
                if (!RegionCommandsUtils.isClassNameValid(cacheListener)) {
                    throw new IllegalArgumentException(CliStrings.format(
                            CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
                            new Object[] { cacheListener }));
                }
            }
        }

        if (cacheLoader != null && !RegionCommandsUtils.isClassNameValid(cacheLoader)) {
            throw new IllegalArgumentException(CliStrings.format(
                    CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
                    new Object[] { cacheLoader }));
        }

        if (cacheWriter != null && !RegionCommandsUtils.isClassNameValid(cacheWriter)) {
            throw new IllegalArgumentException(CliStrings.format(
                    CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
                    new Object[] { cacheWriter }));
        }

        if (evictionMax != null && evictionMax < 0) {
            throw new IllegalArgumentException(CliStrings.format(
                    CliStrings.ALTER_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_EVICTIONMAX_0_IS_NOT_VALID,
                    new Object[] { evictionMax }));
        }

        Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);

        if (targetMembers.isEmpty()) {
            return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
        }

        ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(new RegionAlterFunction(),
                regionFunctionArgs, targetMembers);
        List<CliFunctionResult> regionAlterResults = (List<CliFunctionResult>) resultCollector.getResult();

        TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
        final String errorPrefix = "ERROR: ";
        for (CliFunctionResult regionAlterResult : regionAlterResults) {
            boolean success = regionAlterResult.isSuccessful();
            tabularResultData.accumulate("Member", regionAlterResult.getMemberIdOrName());
            if (success) {
                tabularResultData.accumulate("Status", regionAlterResult.getMessage());
                xmlEntity.set(regionAlterResult.getXmlEntity());
            } else {
                tabularResultData.accumulate("Status", errorPrefix + regionAlterResult.getMessage());
                tabularResultData.setStatus(Result.Status.ERROR);
            }
        }
        result = ResultBuilder.buildResult(tabularResultData);
    } catch (IllegalArgumentException | IllegalStateException e) {
        LogWrapper.getInstance().info(e.getMessage());
        result = ResultBuilder.createUserErrorResult(e.getMessage());
    } catch (RuntimeException e) {
        LogWrapper.getInstance().info(e.getMessage(), e);
        result = ResultBuilder.createGemFireErrorResult(e.getMessage());
    }

    if (xmlEntity.get() != null) {
        persistClusterConfiguration(result,
                () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
    }
    return result;
}

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

private void cerrarFormCrear(boolean bSave, View v) {
    // TODO Usar Layer Indicada
    bSave = false;/*from   ww  w  .  j ava 2 s .c o m*/
    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);
}