Maven / Firebase - Cannot find symbol: variable Firestore Client - java

I am trying to connect to Firebase within my Java project, managed with Maven. I am following Firebase's Getting Started with Cloud Firestore exactly to set up my development environment and initialize Cloud Firestore. This is what my pom.xml and myClass.java looks like.
My dependency in pom.xml:
<dependencies>
<!-- This dependency is added for Firebase usage -->
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>7.1.0</version>
</dependency>
My myClass.java:
package ca.uhn.fhir.example;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.interceptor.ResponseHighlighterInterceptor;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.Firestore;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import java.io.*;
#WebServlet("/*")
public class Example02_SimpleRestfulServer extends RestfulServer {
#Override
protected void initialize() throws ServletException {
// Create a context for the appropriate version
setFhirContext(FhirContext.forR4());
// Register resource providers
// Calls the constructor on the resource provider class?
registerProvider(new Example01_PatientResourceProvider());
// Format the responses in nice HTML
registerInterceptor(new ResponseHighlighterInterceptor());
try {
// Initialize Firebase
// Use a service account
String credentials_path = "/my/path/dfdfdfdfd93.json";
InputStream serviceAccount = new FileInputStream(credentials_path);
GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.build();
FirebaseApp.initializeApp(options);
Firestore db = FirestoreClient.getFirestore();
}
catch (IOException e) {
e.printStackTrace();
}
However, I run into the error:
cannot find symbol [ERROR] symbol: variable FirestoreClient. I have tried adding other related dependencies as shown below, but they are not found/don't seem to fix the problem. I think I am following the Firebase tutorial exactly, so what might I be doing wrong? Why is the FirestoreClient not recognized but many of the other variables are?
<!-- Attempting to fix errors (this doesn't seem to do anything) -->
<!-- https://mvnrepository.com/artifact/com.google.cloud/google-cloud-firestore -->
<!-- <dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
<version>2.2.4</version>
</dependency> -->
<!-- Not found -->
<!-- https://mvnrepository.com/artifact/com.google.firebase/firebase-firestore -->
<!-- <dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-firestore</artifactId>
<version>18.1.0</version>
</dependency> -->
<!--Not found-->
<!-- https://mvnrepository.com/artifact/com.google.firebase/firebase-core -->
<!-- <dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-core</artifactId>
<version>18.0.2</version>
</dependency> -->

This is happening because you did not import the FirestoreClient class, so add the following import to your Example02_SimpleRestfulServer class and it will be fixed:
import com.google.firebase.cloud.FirestoreClient;
NOTE: This should also be in the example in the documentation example you shared, I would recommend you to open a Bug Report in Google's IssueTracker for they to fix that documentation, if you'd like.

Related

Unable to send the logs to Splunk Enterprise local using log4j2

I'm using log4j2 and splunk within java to send logs into my Splunk Enterprise HEC (HTTP Event Collector) Splunk Enterprise is running in my local machine.
I'm doing all log4j2 configuration programmatically. (I know this is not the correct way to do this but I'm still doing this for learning purpose).
I tried to send the logs into Splunk Enterprise directly from postman with the same URL and token and it works fine, but when I tried to send the logs from java using log4j2 I don't get anything in splunk.
My code is =>
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.layout.PatternLayout;
import com.splunk.logging.*;
public class Main {
private static final Logger log;
static {
configureLog4J();
log = LogManager.getLogger(Main.class);
}
public static void configureLog4J() {
ConfigurationBuilder<BuiltConfiguration> builder =
ConfigurationBuilderFactory.newConfigurationBuilder();
// configure a splunk appender
builder.add(
builder.newAppender("splunkH", "SplunkHttp")
.add(
builder.newLayout(PatternLayout.class.getSimpleName())
.addAttribute(
"pattern",
"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
)
)
.addAttribute("sourcetype", "log4j2")
.addAttribute("index", "main")
.addAttribute("url", "http://localhost:8088/services/collector") //I tried this url in postman and its working fine there
.addAttribute("token", "xxx")
.addAttribute("disableCertificateValidation", "true")
);
// configure the root logger
builder.add(
builder.newRootLogger(Level.INFO)
.add(builder.newAppenderRef("splunkH"))
);
// apply the configuration
Configurator.initialize(builder.build());
}//end of configureLog4J
public static void main(String ar[]) {
log.log(Level.INFO, "Hello from log4j2");
log.log(Level.ERROR, "Error from log4j2");
}//end of main method
}//end of class
my POM file
<dependencies>
<dependency>
<groupId>com.splunk.logging</groupId>
<artifactId>splunk-library-javalogging</artifactId>
<version>1.11.4</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.splunk</groupId>
<artifactId>splunk</artifactId>
<version>1.6.5.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>splunk-artifactory</id>
<name>Splunk Releases</name>
<url>https://splunk.jfrog.io/splunk/ext-releases-local</url>
</repository>
</repositories>
I cannot see any logs in splunk. Did I miss something ?
Add .addAttribute("batch_size_count", "1") or make a loop producing 10 log messages, becasue that's the default value of batch_size_count. This has been explained in splunk docs "Configure Log4j 2" section.
By the way, I reckon the services/collector endpoint should be used with JSON messages (e.g. .add(builder.newLayout("JSONLayout"))). Also, you are using a log4j2 version that has the Log4Shell (CVE-2021-44228) vulnerability. It has been fixed in 2.15.0, switch to anything between that and the newest version 2.17.2.
Finally, I share the sentiment of the answers to the question How to configure log4j 2.x purely programmatically? that log4j2 is troublesome to use when configured programmatically. I had issues with it in a cluster env and switching to file configuration solved all my problems.

How to connect with DynamoDB using WebIdentityTokenFileCredentialsProvider

I have the access key, secret key, region and DynamoDB endpoint through which I am able to connect to the database and I have kept the configurations in the application.properties file. Now the requirement is to not to keep the access key and secret keys in the application.properties file and follow the Web identity token from AWS STS. I have removed the access key and secret from the application.properties file and have the below configurations. When I start the application I am getting the below message
Consider defining a bean of type 'com.amazonaws.services.dynamodbv2.AmazonDynamoDB' in your configuration.
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.DefaultTableNameResolver;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverterFactory;
import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
#Configuration
#EnableDynamoDBRepositories(dynamoDBMapperConfigRef = "dynamoDBMapperConfig", basePackages = "com.xyz.repository")
public class DynamoDBConfiguration {
#Value("${aws.dynamodb.endpoint}")
private String endpoint;
#Value("${aws.region}")
private String region;
#Value("${aws.dynamodb.table.name}")
private String tableName;
#Bean
public DynamoDBMapperConfig dynamoDBMapperConfig(TableNameOverride tableNameOverrider) {
DynamoDBMapperConfig.Builder builder = new DynamoDBMapperConfig.Builder();
builder.withTypeConverterFactory(DynamoDBTypeConverterFactory.standard());
builder.withTableNameResolver(DefaultTableNameResolver.INSTANCE);
builder.withTableNameOverride(tableNameOverrider());
return builder.build();
}
#Bean
public TableNameOverride tableNameOverrider() {
return TableNameOverride.withTableNamePrefix(tableName);
}
#Bean
public DynamoDbClient amazonDynamoDB() {
return DynamoDbClient.builder()
.region(Region.of(region))
.credentialsProvider(WebIdentityTokenFileCredentialsProvider.create())
.build();
}
}
In pom.xml I have the below dependency related to AWS.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.15.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>io.github.boostchicken</groupId>
<artifactId>spring-data-dynamodb</artifactId>
<version>5.2.5</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sts</artifactId>
</dependency>
You have more then creds issues in your Java code. The bigger issue is you are mixing up V1 and V2.
The Java DynamoDB V1 API is:
com.amazonaws.services.dynamodbv2.*
The Java DyanamoDB V2 API is:
software.amazon.awssdk.services.dynamodb.*
Now your POM file references V2 API:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.15.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
You should not mix up V1 and V2. You are using V2 for the Service Client, and V1 for the DynamoDBMapperConfig object. This is not good practice and will not work.
Get rid of V1 API and replace with only V2 API. You seem to want to use DynamoDBMapper functionality. For V2, this is now part of Enhanced Client.
Using the DynamoDB Enhanced Client in the AWS SDK for Java 2.x
To see an AWS Tutorial that shows you how to build a Spring BOOT app using the AWS SDK for Java V2 (including the Enhanced Client), see:
Creating the Amazon DynamoDB web application item tracker
In this tutorial, the EnvironmentVariableCredentialsProvider is used to handle the AWS key values.

Facing error "cucumber.runtime.CucumberException: No backends were found."

I am working on Selenium with Cucumber setup and I am facing error when I run the TestRunner file.
cucumber.runtime.CucumberException: No backends were found. Please make sure you have a backend module on your CLASSPATH.
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Automation</groupId>
<artifactId>Cucumber</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Cucumber</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
</project>
I have mapped feature file to StepDefinition file as shown below
Feature file
Feature: Login Functionality
Scenario: Home page default login
Given User is on Home page
When User logs into application with valid credentials
Then User should be logged into application and landing page should be displayed to user
StepDefinition file
package stepDefenition;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;
#RunWith(Cucumber.class)
public class StepDefenition {
#Given("^User is on Home page$")
public void user_is_on_home_page() throws Throwable {
System.out.println("User is on Home Page");
}
#When("^User logs into application with valid credentials$")
public void user_logs_into_application_with_valid_credentials() throws Throwable {
System.out.println("User enters valid credentials and clicks on submit");
}
#Then("^User should be logged into application and landing page should be displayed to user$")
public void user_should_be_logged_into_application_and_landing_page_should_be_displayed_to_user() throws Throwable {
System.out.println("User logged in successfully and landing page is displayed to user with all the details");
}
}
Test Runner File:
package cucumberOption;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "src/test/java/features",
glue="stepDefenition")
public class TestRunner {
}
I am using version:
Neon.3 Release (4.6.3) of Eclipse
Natural 0.7.6 Cucumber plugin
Maven version : Apache Maven 3.6.3
Java Version : java version "1.8.0_241"
structure of the project
I have tried changing versions for java and Junit and adding Io.cucumber dependencies nothing worked.
Added java 1.8 jdk to project build path.
I have viewed all previous threads on this kind of issue.
I did not understand why you using #RunWith annotation in step def class. As cucumber will automatically take care of running it via cucumberRunner, so you can execute your test either from Runner class or via feature files(Scenario level or entire feature file) w/o using any #RunWith annotation. Probably this is the cause of your error here-See below exception:
cucumber.runtime.CucumberException:
Classes annotated with #RunWith(Cucumber.class) must not define any
Step Definition or Hook methods. Their sole purpose is to serve as
an entry point for JUnit. Step Definitions and Hooks should be defined
in their own classes. This allows them to be reused across features.
Offending class: class com.abc.StepDefs.FWFeatureTestSteps (for ex).
Also you need not to have separate junit dependency in pom, only cucumber-junit is enough as long as you want cucumber to get the job done.
Note: Don't mix io.cucumber and info.cukes, use any of them. Mixing both will also cause this very same exception.

Java hadoop api YarnClient doesn't have "init()/start()" function?

I tried maven repo like this:
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-yarn-common</artifactId>
<version>2.7.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-yarn-api -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-yarn-api</artifactId>
<version>2.7.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-yarn-client -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-yarn-client</artifactId>
<version>2.7.2</version>
</dependency>
Then my java code:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.records.*;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.client.api.YarnClientApplication;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
public static void main(String[] args) {
YarnConfiguration yarnConfiguration = new YarnConfiguration();
YarnClient yarnClient = YarnClient.createYarnClient();
yarnClient.init(yarnConfiguration);
yarnClient.start();
}
Intellij ide shows "Cannot solve method init" and "Cannot solve method start".
I then tried to use jar version of 3.1.1 instead of "2.7.2". Same result. So what's wrong with my code and how to fix it?
the init and start method are derived from the AbstractService class.
you need to verify the YarnClient and AbstractService has the same version.
go to YarnClient and check the jar it refer to, then click on the AbstractService parent from the Yarn client and check his version.
change the YarnClient version according to your AbstractService version.
i had the same issue, it works for me . version 2.6.5 .

Cucumber and Selenium Error on Feature

I created a automated test scenario using selenium + cucumber on java, and when I try to execute my test nothing occur. I don't know what I did worng but I think that something happend with my feature, because exist warning on the following messages "No definition found for I try to login on facebook", "No definition found for I put my user "email"", "No definition found for I put my password "pass"" and "No definition found for validate login".
I imported these jars using maven: cucumber-java : 1.2.5/cucumber-junit : 1.2.5/selenium-java : 3.0.1/selenium-firefox-driver : 3.0.1/junit : 4.12
RunTest.java
package com.tdd.facebook;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
format = {"pretty", "html:target/cucumber"},
features = {"src/test/resources"}
)
public class RunTest {
public RunTest() {
// TODO Auto-generated constructor stub
}
}
LoginSteps.java
package com.tdd.facebook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginSteps {
WebDriver driver = null;
#Given("^I try to login on facebook$")
public void i_try_to_login_on_facebook() throws Throwable {
System.setProperty("webdriver.gecko.driver", "C:\\Caio\\Selenium\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
throw new PendingException();
}
#When("^I put my user \"([^\"]*)\"$")
public void i_put_my_user(String email) {
driver.findElement(By.id(email)).click();
driver.findElement(By.id(email)).sendKeys("UserTest");
}
#When("^I put my password \"([^\"]*)\"$")
public void i_put_my_password(String pass){
driver.findElement(By.id(pass)).click();
driver.findElement(By.id(pass)).sendKeys("Test");
}
#Then("^validate login$")
public void validate_login() throws Throwable {
System.out.println("Login OK");
}
public LoginSteps() {
// TODO Auto-generated constructor stub
}
}
Login.feature
Feature: Login on facebook
Scenario: Check if the login is successful
Given I try to login on facebook
When I put my user "email"
When I put my password "pass"
Then validate login
pow.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tdd</groupId>
<artifactId>facebook</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>facebook</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
You need to add glue option to cucumberoptions with the path to the step definition classes. Use glue="com.tdd.facebook". I am not sure about this but you might want to remove the constructor in the runner RunTest.
In the LoginStps class - i_try_to_login_on_facebook() method, you are declaring another driver variable and initializing it. Thus the driver field of the class will remain null. Remove this. Also in the same method you are throwing a k. As you have implemented the step you do not need it anymore.
Also do check if all the jars are imported in the pom. I think you are missing some jars. Check the cucumber java page.

Categories