How to retrieve specific node from firebase database in android based on value

 Sometimes it is needed to retrieve the node based on a value, not the child.

Android+Firebase


you may get some solution like - to get all the nodes first and after that iterate it locally.

Explaining below - 

Let's assume the requirement is to retrieve all the node that has been mobile number = 9999999999.

Structure of the node - 

Firebase Node

The first approach (Not Recommended) - 


In this approach, you will get all the nodes and then you have to iterate to get the required record.

inline number 15-17 i'm iterating all the nodes and removing  the nodes from the list which has the different mobile number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void readAllRequestedFormFromFirebaseDb(){
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("App_DB");
        DatabaseReference childRef = ref.child("AllRequest");
        childRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                // getting list 
                for(DataSnapshot dataSnapshot: snapshot.getChildren()){
                    QueryFormModel post = dataSnapshot.getValue(QueryFormModel.class);
                    queryFormModelArrayList.add(post);

                }
                for(int i=0;i<queryFormModelArrayList.size();i++){
                    if(!queryFormModelArrayList.get(i).getMobileNumber().equalsIgnoreCase("9999999999"))
                        queryFormModelArrayList.remove(i);
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.e("DetailsActivity", "onCancelled:readAllSubmittedRequestFromFirebaseDb:  "+databaseError );
            }
        });
    }
   

Why this approach is not recommended -?

Just assume if you have 1000 records so in this case, you are getting all the nodes first and after that iterating all the nodes to get what exactly the requirement is.
so in short you are doing irrelevant effort and unnecessary extending the network call.
even though it's correct but it will put a question mark on your programming skills.

The second approach (Recommended) - 

In this approach instead of getting all the nodes, you will get only the nodes that have been the mobile number that you passed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void readAllRequestedFormFromFirebaseDb(){
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("App_DB");
        DatabaseReference childRef = ref.child("AllRequest");
        Query queryRef = childRef.orderByChild("mobileNumber").equalTo("9999999999");
        queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                // getting list
                for(DataSnapshot dataSnapshot: snapshot.getChildren()){
                    QueryFormModel post = dataSnapshot.getValue(QueryFormModel.class);
                    queryFormModelArrayList.add(post);
                    /*the above list will have record only
                     with the provided mobile number*/

                }

            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.e("DetailsActivity", "onCancelled:readAllSubmittedRequestFromFirebaseDb:  "+databaseError );
            }
        });
    }
   


That all about this post.👍👍👍

Happy Coding.😍
**********************************************
*************************************************
****************************************************

Log4j Vulnerability

Summary of the Vulnerability


On Dec. 9, 2021, a remote code execution (RCE) vulnerability in Apache log4j 2 was recognized as being taken advantage of in nature. Public proof of concept (PoC) code was delivered and the resulting examination uncovered that double-dealing was unbelievably simple to perform. By presenting a uniquely created solicitation to a weak framework, contingent upon how the framework is designed, an aggressor can teach that framework to download and consequently execute a malicious payload. Because of the disclosure of this adventure being so later, there are as yet numerous servers, both on-premises and inside cloud conditions, that presently can't seem to be fixed. In the same way, as other high seriousness RCE takes advantage of, hitherto, enormous checking movement for CVE-2021-44228 has started on the web with the aim of searching out and taking advantage of unpatched frameworks. We enthusiastically prescribe that associations move up to the most recent rendition (2.16.0) of Apache log4j 2 for all frameworks. This form additionally fixes the less extreme vulnerability CVE-2021-45046, found on Dec. 14.




Log4j vulnerability

Vulnerability Known As Log4j vulnerability, Log4Shell
CVEs Discussed CVE-2021-44228, CVE-2021-45046, CVE-2017-5645, CVE-2019-17571
Types of Vulnerabilities Remote code execution, denial of service

Affected Version

Apache Log4j 2.x <= 2.15.0-rc1

Affected Major Software 

Countless Java-based applications are utilizing log4j as their logging utility and are powerless against this CVE. As far as we could possibly know, essentially the following software might be affected:

  • Apache Struts
  • Apache Solr
  • Apache Druid
  • Apache Flink
  • ElasticSearch
  • Flume
  • Apache Dubbo
  • Logstash
  • Kafka

Background of Apache log4j2

Apache log4j 2 is an open-source Java-based logging system, which is utilized inside various Java applications all over the planet. Contrasted and the first log4j 1.X delivery, log4j 2 resolved issues with the past discharge and offered a module design for clients. On Aug. 5, 2015, log4j 2 turned into the standard rendition, and all of the past form log4j clients were prescribed to move up to log4j 2. Apache log4j 2 is broadly utilized in numerous well-known programming applications, like Apache Struts, ElasticSearch, Redis, Kafka, and others.

While providing a simple and adaptable client experience, Apache log4j 2 has generally been defenseless against the process and deserialize client inputs. Two past deserialization weaknesses, CVE-2017-5645 and CVE-2019-17571, were recently found, bringing about code infusion and further RCE because of an absence of essential handling against gave client input information.
Spring-Boot-starter-log4j2.

  • CVE-2017-5645: For Apache log4j 2.x before 2.8.2, the log4j servers will deserialize any log events received from other applications through TCP or UDP socket servers. If a crafted binary payload is being sent using this vulnerability, it can lead to arbitrary code execution.
  • CVE-2019-17571: For Apache log4j versions from 1.2 (up to 1.2.17), the SocketServer class is vulnerable to deserialization of untrusted data, which leads to remote code execution if combined with a deserialization gadget.

Description of the Vulnerability (CVE-2021-44228)

The Apache log4j library takes into account engineers to log different information inside their applications. In specific conditions, the information being logged starts from client input. Should this client input contain unique characters and be consequently logged inside the setting of log4j, the Java strategy query will, at last, be called to execute the client characterized far off Java class in the LDAP server. This will thus prompt RCE on the casualty server that utilizes the helpless log4j 2 examples.

Underlying Case Analysis

Assuming we investigate, we find that log4j 2.x backings a mechanism called lookups, which is generally used to set up the log4j config deftly for clients. The authority presentation about Lookups is as per the following:

Queries give a method for adding qualities to the log4j setup at self-assertive spots. They are a specific sort of Plugin that carries out the StrLookup interface.

The ordinary client can advantageously and deftly add esteems to the setup at discretionary spots with the predesigned design by utilizing this element. Exhaustively, when calling the log strategy in the application, log4j 2.x will call the configuration technique to really look at the particular characters ${ in each log.

Should these characters be available, the Java technique query will be called to track down strings later the characters ${ and afterward supplant the articulation later the characters ${ with the genuine worth found previously. For instance, when calling the log work in the application to log the substance displayed in Figure 1, the strings java:runtime, java:vm, and java:os later the characters ${ will be considered as the boundary of the query strategy lastly supplanted with the comparing esteems, like Java(TM) SE Runtime Environment (assemble 1.7.0_67-b01) from Oracle Corporation, Java HotSpot(TM) 64-Bit Server VM (fabricate 24.65-b04, blended mode, and Windows 7 6.1 Service Pack 1, design: amd64-64.

1 -Java lookup example


There are several types of lookup upheld by the feature lookups, like Jndi Lookup, JVM Input Arguments Lookup (JMX), and Web Lookup. The Jndi query permits factors to be recovered by JNDI. In the Jndi Lookup, a few conventions are upheld to make the distant query, like LDAP and RMI. Assuming the log incorporates the strings displayed in Figure 2, the Java strategy query will be called to find the string jndi:logging/setting name.

2 -Legitimate JNDI lookup string


By considering the log content is usually exposed to users and can be easily controlled by the attacker in many applications very easily, once the attacker controls the string as shown in Figure 3 and sets a malicious Java class on an attacker-controlled LDAP server, the lookup method will be used to execute the malicious Java class on the remote LDAP server.

3 -Malicious JNDI lookup string with LDAP



The log4j library is a powerfully strong and trusted log framework with very flexible features supported. However, convenient features often involve potential security issues at the same time. Without careful user input filtering and strict input data sanitization, blind trust in user input may lead to severe security issues.

Exploit Analysis

Exploit Code for the CVE-2021-44228 vulnerability has been made publicly available in no time. Any user input or logs hosted by a Java application using the vulnerable version of log4j 2.x may be exposed to this attack very easily, depending on how logging is implemented within the Java application.


Fix and Bypass: Fix Added for CVE-2021-45046

With the authority Apache fix being delivered, 2.15.0-rc1 was at first answered to have fixed the CVE-2021-44228 vulnerability. In any case, an ensuing detour was found. A recently delivered 2.15.0-rc2 adaptation was thus delivered, which secures clients against this vulnerability.

On Dec. 14, it was found that the fix delivered in Log4j 2.15.0 was inadequate. CVE-2021-45046 was doled out for the new weakness found. Per our fundamental investigation, the impact of this vulnerability is the denial of service (DoS) however not full remote code execution. This vulnerability is less serious than CVE-2021-44228, yet clients should refresh Log4j to variant 2.16.0 to fix this vulnerability.

What Next - 

The CVE-2021-44228 vulnerability is as yet being effectively researched to appropriately recognize the full scope severity. Given the data as of now accessible, this vulnerability might have a high effect as of now and later on. Most of the applications being affected are widely used in corporate networks as well as home networks. Clients are urged to do whatever it may take to guarantee they are ensured against this vulnerability, as illustrated underneath.

JDK 18: What to expect in Java 18

Due in March 2022, Java 18 has attracted recommendations to hatch the vector API, preview pattern matching for switch statements, and embrace UTF-8 as the default character set. 



Due in March 2022, Java 18 keeps on adding highlights, with nine component recommendations being considered for it up until this point, including the deprecation of finalization, a capability that was intended to help avoid resource leaks but has brought with it risks of unconstrained behavior and unpredictable latency.


The OpenJDK page for Java Development Kit (JDK) 18 records the accompanying elements as authoritatively focusing on JDK 18 as of November 24: a service provider interface, a basic web server, a vector API, code snippets, a reimplementation of core reflection, a UTF-8 charset, the second incubator of a foreign function and memory API, and the second preview of pattern matching for switch statements. Deprecation of finalization is proposed to target JDK 18 in the JDK Enhancement Proposal (JEP) record.


General accessibility is expected on March 22, 2022, following ramp-down stages happening December 9, 2021, and January 20, 2022. Discharge applicants are expected on February 10 and February 24 of the following year.



Upcoming feature Specifics of the JDK 18 proposals includes:


Deprecate finalization for removal in an upcoming versions release.

 Finalizer has defects that cause critical true issues in terms of safety/security, in terms of execution/performance, in terms of dependability/reliability, and in terms of viability/maintainability. It also has a tight coupling difficult programming model. 


Finalization is enabled by default in java programming for now but it can be disabled to facilitate early testing in the future. It will be disabled by default in a feature release and removed altogether in a later release in the future. 


The proposal calls for a command-line option to disable or deprecate finalization and deprecation of all finalizers and finalization methods in the standard Java API. The goals of the proposal include helping java developers and programmers to understand the dangers of finalization, preparing developers for its eventual removal, and providing simple easy tools to help detect reliance on finalization. Introduced in Java 1.0, finalization was intended to help avoid resource leaks.


 A class can declare a finalizer — the method protected void finalize() — whose body releases any underlying resource. The garbage collector will schedule the finalizer of an unreachable object to be called before it reclaims object memory this is what happening till now; in turn, the finalize method can take actions such as calling the object’s close. This seems like an effective safety net for preventing resource leaks, but flaws and drawbacks exist including unpredictable latency, with a long time passing between when an object becomes unreachable and when its finalizer is called; unconstrained behavior, with finalizer code able to take any action, including resurrecting an object and making it reachable again; finalizer is always enabled, with no explicit registration mechanism, and finalizers can run on unspecified threads in an arbitrary order. Given the problems with finalization, developers are advised to use alternative techniques to avoid resource leaks, namely try-with-resources statements and cleaners.


For the Internet-address goal SPI, 

the proposition is to characterize an SPI for the host and name address goal with the goal that Inet. The address can utilize resolvers other than the stage's underlying resolver. Inspirations for this work incorporate better enablement of Project Loom, for simultaneousness and new programming models in Java, alongside coordinating new organization conventions, customization, and empowering testing. The proposition doesn't include fostering an option resolver for the JDK.


The second review of example coordinating for switch,

 in which the Java language would be upgraded with design coordinating for switch articulations and explanations, alongside expansions to the language of examples. This was seen in JDK 17. Stretching out design coordinating to change permits an articulation to be tried against various examples, each with a particular activity, so intricate information situated questions can be communicated briefly and securely.


The reimplementation of core reflection with technique handles would reimplement lang.reflect.Method, Constructor, and Field on top of java.lang.invoke strategy handles. Having method handles fill in as the hidden instrument for reflection will diminish support and improvement expenses of both the java.lang.reflect and java.lang.invoke APIs.


With the simple web server proposal, 

a command-line tool would be provided to start a minimal web server that serves static files only. No CGI or servlet-like functionality is available. The tool will be useful for prototyping, ad-hoc coding, and testing, particularly in educational contexts. The goals of the plan include offering an out-of-the-box static HTTP file server with easy setup and minimal functionality, reducing developer activation energy and making the JDK more approachable, and providing a default implementation via the command line together with a small API for programmatic creation and customization. Providing a feature-rich or commercial-grade server is not a goal of the proposal.


A second incubation of a foreign function and memory API,

in which an API is introduced through which Java programs can interoperate with code and data outside of the Java runtime. By invoking foreign functions – code outside the JVM – and by safely accessing foreign memory – memory not managed by the JVM – the API lets Java programs call native libraries and process native data without the brittleness and danger of JNI (Java Native Interface). The intent is to replace JNI with a superior, pure Java development model. This API was incubated in JDK 17. For JDK 18, refinements would be incorporated, based on feedback, such as support for more carriers such as Boolean and MemoryAddress in memory access var handles, and a new API to copy Java arrays to and from memory segments.


The vector API would be incubated for a third time in JDK 18,

 having previously been incubated in JDK 16 and JDK 17. This proposal would express vector computations that compile at run time to optimal vector instructions on supported CPU architectures, achieving performance superior to equivalent scalar computations. Vector operations express a degree of parallelization enabling more work to be done on a single CPU cycle, thus producing significant performance improvements. The platform-agnostic vector API aims to provide a way to write complex algorithms in Java, using the existing HotSpot auto-vectorizer but with a user model that makes vectorization more predictable. JDK 18 would also add support for the ARM Scalar Vector Extension platform and improve the performance of vector operations that accept masks on architectures that support masking in hardware.


Specifying UTF-8 as the default charset of the standard Java APIs,

 UTF-8 is a variable-wide character encoding for electronic communication and is considered the web’s standard charset. The charset is a character encoding capable of encoding all characters on the web. Through this change, APIs that depend on the default charset will behave consistently across all implementations, operating systems, locales, and configurations. The proposal is not intended to define new Java-standard or JDK-specific APIs. Proponents of the proposal expect that applications in many environments will see no impact from Java’s choice of UTF-8, like MacOS, many Linux distributions, and many server applications already support UTF-8. However, there is risk in other environments, the most obvious being that applications depending on the default charset will behave incorrectly when processing data produced when the default charset was unspecified. Data corruption may silently occur. The main impact is expected to befall users of Windows systems in Asian locales and possibly some server environments in Asia and other locales.


Code snippets in Java API documentation,

including the presentation of a @snippet tag for JavaDoc's Standard Doclet, to improve on the incorporation of model source code in the API documentation. Among objectives of the arrangement is working with the approval of source code parts by giving API admittance to those pieces. While accuracy is the obligation of the creator, upgraded support in JavaDoc and related instruments can make it more straightforward to accomplish. Different objectives incorporate empowering present-day styling, for example, sentence structure featuring, just as the programmed linkage of names to assertions, and empowering better IDE support for making and altering pieces. The proposition takes note that creators of API documentation regularly remember parts of source code for documentation remarks.






That's all about this post.

Thanks a bunch for being here.
#stayhealthy
#takeCare

*************
******************
*************************


Find another must-read post.