How to fix This “All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes)”

I am creating an app that uses firebase authentication for login and registration but I keep getting sudden crashes as soon as I run the application. I'm getting a warning in my Gradle.build file at the app level. The warning says

I am creating an app that uses firebase authentication for login and registration but I keep getting sudden crashes as soon as I run the application. I'm getting a warning in my Gradle.build file at the app level. The warning says

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0, 26.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:support-media-compat:26.1.0

I've tried changing com.android.support:appcompat-v7:28.0.0 to v7:26.0.1 and 27.1.0 but none of them solved the problem.

My build.gradle file is as follows:

apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
applicationId "com.project.tck.rescueme_responder"
minSdkVersion 14
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
}
apply plugin: 'com.google.gms.google-services'

I expect a login that authenticates using FireBase when I run the application but then the application crashes each time I run it.

How to convert XML to HTML using Java libraries

How to convert XML to HTML using Java libraries

In this tutorial, we'll describe how to convert XML to HTML using common Java libraries and template engines – JAXP, StAX, Freemarker, and Mustache

1. An XML to Unmarshal

Let's start off with a simple XML document that we'll unmarshal into a suitable Java representation before we convert it into HTML. We'll bear in mind a few key goals:

  1. Keep the same XML for all of our samples
  2. Create a syntactically and semantically valid HTML5 document at the end
  3. Convert all XML elements into text

Let's use a simple Jenkins notification as our sample XML:

<?xml version="1.0" encoding="UTF-8"?>
<notification>
    <from>[email protected]</from>
    <heading>Build #7 passed</heading>
    <content>Success: The Jenkins CI build passed</content>
</notification>

And it's pretty straightforward. It includes a root element and some nested elements.

We'll aim to remove all of the unique XML tags and print out key-value pairs when we create our HTML file.

2. JAXP

Java Architecture for XML Processing (JAXP) is a library that was intended to expand the functionality of the popular SAX Parser with additional DOM support. JAXP provides the ability to marshal and unmarshal XML-defined objects into and from POJOs using SAX Parser. We'll also make use of the built-in DOM helpers.

Let's add the Maven dependency for JAXP to our project:

<dependency>
    <groupId>javax.xml</groupId>
    <artifactId>jaxp-api</artifactId>
    <version>1.4.2</version>
</dependency>

2.1. Unmarshalling Using DOM Builder

Let's begin by first unmarshalling our XML file into a Java Element object:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
 
Document input = factory
  .newDocumentBuilder()
  .parse(resourcePath);
Element xml = input.getDocumentElement();

2.2. Extracting the XML file contents in a Map

Now, let's build a Map with the relevant contents of our XML file:

Map<String, String> map = new HashMap<>();
map.put("heading",
  xml.getElementsByTagName("heading")
    .item(0)
    .getTextContent());
map.put("from", String.format("from: %s",
  xml.getElementsByTagName("from")
    .item(0)
    .getTextContent()));
map.put("content",
  xml.getElementsByTagName("content")
    .item(0)
    .getTextContent());

2.3. Marshalling Using DOM Builder

Marshalling our XML into an HTML file is a little more involved.

Let's prepare a transfer Document that we'll use to write out the HTML:

Document doc = factory
  .newDocumentBuilder()
  .newDocument();

Next, we'll fill the Document with the Elements in our map:

Element html = doc.createElement("html");
 
Element head = doc.createElement("head");
html.setAttribute("lang", "en");
 
Element title = doc.createElement("title");
title.setTextContent(map.get("heading"));
 
head.appendChild(title);
html.appendChild(head);
 
Element body = doc.createElement("body");
 
Element from = doc.createElement("p");
from.setTextContent(map.get("from"));
 
Element success = doc.createElement("p");
success.setTextContent(map.get("content"));
 
body.appendChild(from);
body.appendChild(success);
 
html.appendChild(body);
doc.appendChild(html);

Finally, let's marshal our Document object using a TransformerFactory:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
 
try (Writer output = new StringWriter()) {
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(new DOMSource(doc), new StreamResult(output));
}

If we call output.toString(), we'll get the HTML representation.

3. StAX

Another library we can use is the Streaming API for XML (StAX). Like JAXP, StAX has been around for a long time — since 2004.

The other two libraries simplify parsing XML files. That's great for simple tasks or projects but less so when we need to iterate or have explicit and fine-grained control over element parsing itself. That's where StAX comes in handy.

Let's add the Maven dependency for the StAX API to our project:

<dependency>
    <groupId>javax.xml.stream</groupId>
    <artifactId>stax-api</artifactId>
    <version>1.0-2</version>
</dependency>

3.1. Unmarshalling Using StAX

We'll use a simple iteration control flow to store XML values into our Map:

XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
XMLStreamReader input = null;
try (FileInputStream file = new FileInputStream(resourcePath)) {
    input = factory.createXMLStreamReader(file);
 
    Map<String, String> map = new HashMap<>();
    while (input.hasNext()) {
        input.next();
        if (input.isStartElement()) {
            if (input.getLocalName().equals("heading")) {
                map.put("heading", input.getElementText());
            }
            if (input.getLocalName().equals("from")) {
                map.put("from", String.format("from: %s", input.getElementText()));
            }
            if (input.getLocalName().equals("content")) {
                map.put("content", input.getElementText());
            }
        }
    }
} finally {
    if (input != null) {
        input.close();
    }
}

3.2. Marshalling Using StAX

Now, let's use our map and write out the HTML:

try (Writer output = new StringWriter()) {
    XMLStreamWriter writer = XMLOutputFactory
      .newInstance()
      .createXMLStreamWriter(output);
 
    writer.writeDTD("<!DOCTYPE html>");
    writer.writeStartElement("html");
    writer.writeAttribute("lang", "en");
    writer.writeStartElement("head");
    writer.writeDTD("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
    writer.writeStartElement("title");
    writer.writeCharacters(map.get("heading"));
    writer.writeEndElement();
    writer.writeEndElement();
 
    writer.writeStartElement("body");
 
    writer.writeStartElement("p");
    writer.writeCharacters(map.get("from"));
    writer.writeEndElement();
 
    writer.writeStartElement("p");
    writer.writeCharacters(map.get("content"));
    writer.writeEndElement();
 
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
}

Like in the JAXP example, we can call output.toString() to get the HTML representation.

4. Using Template Engines

As an alternative to writing the HTML representation, we can use template engines. There multiple options in the Java ecosystem. Let's explore some of them.

4.1. Using Apache Freemarker

Apache FreeMarker is a Java-based template engine for generating text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.

In order to use it, we'll need to add the freemarker dependency to our Maven project:

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.29</version>
</dependency>

First, let's create a template using the FreeMarker syntax:

<!DOCTYPE html>
<html lang="en">
<head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>${heading}</title>
</head>
<body>
<p>${from}</p>
<p>${content}</p>
</body>
</html>

Now, let's reuse our map and fill the gaps in the template:

Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
cfg.setDirectoryForTemplateLoading(new File(templateDirectory));
cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString());
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
cfg.setFallbackOnNullLoopVariable(false);
Template temp = cfg.getTemplate(templateFile);
try (Writer output = new StringWriter()) {
    temp.process(staxTransformer.getMap(), output);
}

4.2. Using Mustache

Mustache is a logic-less template engine. Mustache can be used for HTML, config files, source code — pretty much anything. It works by expanding tags in a template using values provided in a hash or object.

To use it, we'll need to add the mustache dependency to our Maven project:

<dependency>
    <groupId>com.github.spullara.mustache.java</groupId>
    <artifactId>compiler</artifactId>
    <version>0.9.6</version>
</dependency>

Let's start creating a template using the Mustache syntax:

<!DOCTYPE html>
<html lang="en">
<head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>{{heading}}</title>
</head>
<body>
<p>{{from}}</p>
<p>{{content}}</p>
</body>
</html>

Now, let's fill the template with our map:

MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(templateFile);
try (Writer output = new StringWriter()) {
    mustache.execute(output, staxTransformer.getMap());
    output.flush();
}
5. The Resulting HTML

In the end, with all our code samples, we'll get the same HTML output:

<!DOCTYPE html>
<html lang="en">
<head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Build #7 passed</title>
</head>
<body>
<p>from: [email protected]</p>
<p>Success: The Jenkins CI build passed</p>
</body>
</html>
6. Conclusion

In this tutorial, we've learned the basics of using JAXP, StAX, Freemarker, and Mustache to convert XML into HTML.

A Java Web Application Without a web.xml

A Java Web Application Without a web.xml

Learn how to use the Java Servlet 3.0 annotations instead of a web.xml file...

1. Overview

In this tutorial, we’re creating a Java web application using Servlet 3.0+.

We’ll take a look at three annotations – @WebServlet@WebFilter, and @WebListener – that can help us nix our web.xml files.

2. The Maven Dependency

In order to use these new annotations, we need to include the javax.servlet-api dependency:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

3. XML Based Configuration

Before Servlet 3.0, we’d configure a Java web application in a web.xml file:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
    <listener>
        <listener-class>com.baeldung.servlets3.web.listeners.RequestListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>uppercaseServlet</servlet-name>
        <servlet-class>com.baeldung.servlets3.web.servlets.UppercaseServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>uppercaseServlet</servlet-name>
        <url-pattern>/uppercase</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>emptyParamFilter</filter-name>
        <filter-class>com.baeldung.servlets3.web.filters.EmptyParamFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>emptyParamFilter</filter-name>
        <url-pattern>/uppercase</url-pattern>
    </filter-mapping>
</web-app>

Let’s start replacing each configuration section with the respective annotations introduced in Servlet 3.0.

4. Servlets

JEE 6 shipped with Servlet 3.0 which enables us to use annotations for servlet definitions, minimizing the use of a web.xml file for a web application.

For example, we can define a servlet and expose it with the *@WebServlet annotation*

Let’s define one servlet for the URL pattern /uppercase. It will transform the value of the input request parameter to uppercase:

@WebServlet(urlPatterns = "/uppercase", name = "uppercaseServlet")
public class UppercaseServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {
        String inputString = request.getParameter("input").toUpperCase();
 
        PrintWriter out = response.getWriter();
        out.println(inputString);
    }
}

Note that we defined a name for the servlet (*uppercaseServlet) that we can now reference.* We’ll make use of this in the next section.

With the @WebServlet annotation, we’re replacing the servlet and servlet-mapping sections from the web.xml file.

5. Filters

Filter is an object used to intercept requests or responses, performing pre- or post-processing tasks.

We can define a filter with the *@WebFilter annotation.*

Let’s create a filter to check if the input request parameter is present:

@WebFilter(urlPatterns = "/uppercase")
public class EmptyParamFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
        String inputString = servletRequest.getParameter("input");
 
        if (inputString != null && inputString.matches("[A-Za-z0-9]+")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletResponse.getWriter().println("Missing input parameter");
        }
    }
 
    // implementations for other methods
}

With the @WebFilter annotation, we’re replacing the filter and filter-mapping sections from the web.xml file.

6. Listeners

We’ll often need to trigger actions based on certain events. This is where listeners come to the rescue. These objects will listen for an event and execute the behavior we specify.

Like previously, we can define a listener with the *@WebListener annotation.*

Let’s create a listener that counts each time we perform a request to the server. We’ll implement ServletRequestListener, listening for _ServletRequestEvent_s:

@WebListener
public class RequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent event) {
        HttpServletRequest request = (HttpServletRequest)event.getServletRequest();
        if (!request.getServletPath().equals("/counter")) {
            ServletContext context = event.getServletContext();
            context.setAttribute("counter", (int) context.getAttribute("counter") + 1);
        }
    }
 
    // implementations for other methods
}

Note that we are excluding the requests to the URL pattern /counter.

With the @WebListener annotation, we’re replacing the listener section from the web.xml file.

7. Build and Run

For those following along, note that for testing, there’s a second servlet we’ve added for the /counter endpoint that simply returns the counter servlet context attribute.

So, let’s use Tomcat as the application server.

If we are using a version of maven-war-plugin prior to 3.1.0, we’ll need to set the property failOnMissingWebXml to false.

Now, we can deploy our .war file to Tomcat, and access to our servlets.

Let’s try out our /uppercase endpoint:

curl http://localhost:8080/spring-mvc-java/uppercase?input=texttouppercase
 
TEXTTOUPPERCASE

And we should also see how our error handling looks:

curl http://localhost:8080/spring-mvc-java/uppercase
 
Missing input parameter

And finally, a quick test of our listener:

curl http://localhost:8080/spring-mvc-java/counter
 
Request counter: 2

8. XML Still Needed

Even, with all the features introduced in Servlet 3.0, there are some use cases where we’ll still need a web.xml file, among them:

  • We can’t define the filter order with annotations – we still need the section if we have multiple filters that we need to be applied in a particular order
  • To define a session timeout, we still need to use the section
  • We still need the element for container-based authorization
  • And to specify welcome files, we’ll still need a section

Or, Servlet 3.0 also introduced some programmatic support via ServletContainerInitializer, too, which can also fill in some of these gaps.

9. Conclusion

In this tutorial, we configured a Java web Application without using the web.xml file by exercising the equivalent annotations.

As always, the source code for this tutorial can be found on GitHub. Additionally, an application using the traditional web.xml file can also be found on GitHub.

For a Spring-based approach, head over to our tutorial web.xml vs. Initializer with Spring.

XML Serialisation using JAXB(In French)

A small example to serialize any java object into an XML file <span class="ql-emojiblot" data-name="sunglasses"><span contenteditable="false"><span class="ap ap-sunglasses">😎</span></span></span>.

A small example to serialize any java object into an XML file 😎.