yesterday i linked my github to an azure web app service
my repo built with rest requests and some of them is working with loading data from firestore based databased , i ran it all on localhost on the tomcat embedded server that comes with spring
,got the web app in the air and my post request which getting resource from firebase , the post request got me an internal 500 server so i check the app insights feature to check what exception i get
java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist.
at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:165)
at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:136)
my init code for fire base is:
package Model;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;
#Service
public class FBInitialize {
#PostConstruct
public void initialize() {
try {
String fileName = "name of json file with Credential.json";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile());
FileInputStream serviceAccount = new FileInputStream(file);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://qr-database-my data base url")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}
}
i checked on the logs and i did got the request i just getting this exception is anyone ever encounter
this exception ?
by the way on initiazlizeApp method the getIntstance methood is being called.
Edit:
found where the exception was thrown from :
public static FirebaseApp getInstance(#NonNull String name) {
synchronized(appsLock) {
FirebaseApp firebaseApp = (FirebaseApp)instances.get(normalize(name));
if (firebaseApp != null) {
return firebaseApp;
} else {
List<String> availableAppNames = getAllAppNames();
String availableAppNamesMessage;
if (availableAppNames.isEmpty()) {
availableAppNamesMessage = "";
} else {
availableAppNamesMessage = "Available app names: " + Joiner.on(", ").join(availableAppNames);
}
String errorMessage = String.format("FirebaseApp with name %s doesn't exist. %s", name, availableAppNamesMessage);
throw new IllegalStateException(errorMessage);
}
}
}
The problem may be the source code version on github. Please check build.gradle file under android/app folder.
Add the following line:
apply plugin:'com.google.gms.google-services'
Related Posts:
1. How to solve Exception Error: FirebaseApp with name [DEFAULT] doesn't exist?
2. FirebaseApp with name [DEFAULT] doesn't exist
im working with maven , also i figured it out that its has something with the json file with the google credentials location because repackaging the file changing the root content to BOOT-INF so i took the json file content put it in a String and cast it to Inputstream so the Initializeapp and the init would be independent but it still no joy :(
new update:
now i get a different exception I think its about security
java.lang.IllegalStateException: Could not find TLS ALPN provider; no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available
agian im working with maven and not on android
Related
The title really says it all. I need each instance running to be aware of what the other instances are, including their IP addresses. Is there an EB API call to do that? Or maybe a more generic way in AWS?
The AWS Elastic Beanstalk SDK exposes methods that provide details about both the Environment and Applications. (Not clear what you mean by I need each instance running to be aware of what the other instances are)
Anyhow -- you can get a list of applications and get details about those EB apps. For example, you can get the status (an EB app that is running will have a status value Ready) and the app URL (not the IP). SO you can get at the details you are looking for with the SDK.
Running this code returns details that you see the AWS Management Console -- such as:
The application name is VideoAnalyzer
The Environment ARN is arn:aws:elasticbeanstalk:us-east-1:xxxxxx047983:environment/VideoAnalyzer/Videoanalyzer-env
The Endpoint URL is awseb-AWSEB-xxxxxxY1BQF02-xxxx6689.us-east-1.elb.amazonaws.com
The status is Ready
I will show you the code in Java SDK v2.
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient;
import software.amazon.awssdk.services.elasticbeanstalk.model.DescribeApplicationsResponse;
import software.amazon.awssdk.services.elasticbeanstalk.model.ApplicationDescription;
import software.amazon.awssdk.services.elasticbeanstalk.model.DescribeEnvironmentsRequest;
import software.amazon.awssdk.services.elasticbeanstalk.model.DescribeEnvironmentsResponse;
import software.amazon.awssdk.services.elasticbeanstalk.model.EnvironmentDescription;
import software.amazon.awssdk.services.elasticbeanstalk.model.ElasticBeanstalkException;
import java.util.List;
//snippet-end:[eb.java2.describe_app.import]
/**
* Before running this Java V2 code example, set up your development environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class DescribeApplications {
public static void main(String[] args) {
Region region = Region.US_EAST_1;
ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder()
.region(region)
.build();
describeApps(beanstalkClient);
}
//snippet-start:[eb.java2.describe_app.main]
public static void describeApps(ElasticBeanstalkClient beanstalkClient) {
try {
DescribeApplicationsResponse applicationsResponse = beanstalkClient.describeApplications();
List<ApplicationDescription> apps = applicationsResponse.applications();
for (ApplicationDescription app: apps) {
System.out.println("The application name is "+app.applicationName());
DescribeEnvironmentsRequest desRequest = DescribeEnvironmentsRequest.builder()
.applicationName(app.applicationName())
.build();
DescribeEnvironmentsResponse res = beanstalkClient.describeEnvironments(desRequest) ;
List<EnvironmentDescription> envDesc = res.environments();
for (EnvironmentDescription desc: envDesc) {
System.out.println("The Environment ARN is "+desc.environmentArn());
System.out.println("The Endpoint URL is "+ desc.endpointURL());
System.out.println("The status is "+ desc.status());
}
}
} catch (ElasticBeanstalkException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
//snippet-end:[eb.java2.describe_app.main]
}
Whatever I tried I cannot set an extension property on a User object, here is a reproducible piece of code:
public async Task CleanTest(string extName)
{
ExtensionProperty ep = new ExtensionProperty
{
Name = extName,
DataType = "String",
TargetObjects = { "User" }
};
App app = (App)(await _client.Applications.Where(a => a.AppId == _managementAppClientId).ExecuteSingleAsync());
app.ExtensionProperties.Add(ep);
await app.UpdateAsync();
GraphUser user = (GraphUser)(await _client.Users.Where(u => u.UserPrincipalName.Equals("email")).ExecuteSingleAsync());
string propName = FormatExtensionPropertyName(extName); //formats properly as extesion_xxx_name
user.SetExtendedProperty(propName, "testvalue");
//user.SetExtendedProperty(extName, "testvalue");
await user.UpdateAsync(); // fails here
}
user.UpdateAsync() according to Fiddler doesn't even go out and application fails with an exception:
"The property 'extension_e206e28ff36244b19bc56c01160b9cf0_UserEEEqdbtgd3ixx2' does not exist on type 'Microsoft.Azure.ActiveDirectory.GraphClient.Internal.User'. Make sure to only use property names that are defined by the type."
This issue is also being tracked here:
https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console/issues/28
I've got an alternative workaround for this bug, for those that want to use the version 5.7 OData libraries rather than redirecting to the v5.6.4 versions.
Add a request pipeline configuration handler.
// initialize in the usual way
ActiveDirectoryClient activeDirectoryClient =
AuthenticationHelper.GetActiveDirectoryClientAsApplication();
// after initialization add a handler to the request pipline configuration.
activeDirectoryClient.Context
.Configurations.RequestPipeline
.OnMessageWriterSettingsCreated(UndeclaredPropertyHandler);
In the handler, change the ODataUndeclaredPropertyBehaviorKinds value on the writer settings to SupportUndeclaredValueProperty.
private static void UndeclaredPropertyHandler(MessageWriterSettingsArgs args)
{
var field = args.Settings.GetType().GetField("settings",
BindingFlags.NonPublic | BindingFlags.Instance);
var settingsObject = field?.GetValue(args.Settings);
var settings = settingsObject as ODataMessageWriterSettings;
if (settings != null)
{
settings.UndeclaredPropertyBehaviorKinds =
ODataUndeclaredPropertyBehaviorKinds.SupportUndeclaredValueProperty;
}
}
Just in case you still looking for solution to this problem or someone else is facing the same issue:
I got similar issue and it looks like, at least for me, the problem was in latest version of "Microsoft.Data.Services.Client" package - 5.7.0 (or in one of it dependencies). When I downgraded to previous version - 5.6.4 it worked as a charm.
I had same symptoms - updating of extended property was failing even w/o any request is made (also used Fiddler)
Hope it helps!
Artem Liman
I have been trying to use the javamail api to read gmail inbox messages. I found the following code on the internet. I'm trying to run this on Eclipse, but it is failing with an "Invalid credentials exception". I have mail.jar, activation.jar, imap.jar and other jar files in the lib directory of the web-app.
Any ideas as to why I am receiving this exception ? Thanks.
javax.mail.AuthenticationFailedException: Invalid credentials n67if632335wep.219
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:665)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at org.mb.mail.MailReader.main(MailReader.java:23)
package org.mb.mail;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.*;
public class MailReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}
Throw away that code and use this code from the JavaMail FAQ, where you'll also find lots of other helpful tips, including debugging tips.
If you see this exception you are in correct path, just you need to change the mail id or create a new gmail id which will have less security.(for example a primary gmail account is much configured in smartphones and its highly secured with google with Oauth2.0, so that gmail account connection will be blocked by google but when you tried with alternate gmail id or gmail id which not configured in mobile can be easily get connected)
Previously this issue broke my head finally got fixed. Thanks
I'm creating unit tests for our application, and I'm stuck. For testing I have a simple HelloWebServlet that I'm protecting via annotations:
#WebServlet(urlPatterns = {"/hello"})
#ServletSecurity(#HttpConstraint(rolesAllowed = {"user"}))
I'm starting the server the way that's always worked OK (see [1]) and creating users (see [2]) seems to be OK because output from CommandRunner calls to list-file-users and list-file-groups are correct, but I'm getting this error when I try to connect using the username and password:
WARNING: WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Unable to locate a login configuration
The calling code uses the Jersey client API:
#Test
public void testPingServletLoggedIn() {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(GlassFishServerHelper.USERNAME, "xx"));
WebResource webResource = client.resource(GlassFishServerHelper.getBaseUri() + "/hello");
ClientResponse clientResponse = webResource
.accept(MediaType.TEXT_PLAIN)
.get(ClientResponse.class); // #GET
assertEquals(ClientResponse.Status.OK, clientResponse.getClientResponseStatus());
}
(Note: I tried to set javax.enterprise.system.core.security.level=FINE but that call failed with: PlainTextActionReporterFAILURENo configuration found for javax.enterprise.system.core.security . Drat!)
I've tried this against both glassfish-embedded-all-3.1.2.jar (our production version) and glassfish-embedded-all-3.2-b06.jar with the same results. What do you think would solve this? I've struggled and succeeded way too many times with GFE to give up without a fight!
==== [1] server startup (excerpt) ====
public static void startServer() {
GlassFishProperties gfProps = new GlassFishProperties();
gfProps.setPort("http-listener", PORT);
GLASSFISH = GlassFishRuntime.bootstrap().newGlassFish(gfProps);
GLASSFISH.start();
enableDefaultPrincipleToRoleMapping();
createUsersAndGroups();
ScatteredArchive archive = new ScatteredArchive(WEB_APP_NAME, ScatteredArchive.Type.WAR);
File classesDir = new File("out/production/simple-security-servlet-test");
archive.addClassPath(classesDir);
DEPLOYER = GLASSFISH.getDeployer();
APP_NAME = DEPLOYER.deploy(archive.toURI());
private static void enableDefaultPrincipleToRoleMapping() throws GlassFishException {
CommandRunner cr = GLASSFISH.getCommandRunner();
CommandResult result = cr.run("set",
"server-config.security-service.activate-default-principal-to-role-mapping=true");
}
==== [2] user creation (excerpt) ====
private static void createUsersAndGroups() throws GlassFishException {
CommandRunner commandRunner = GLASSFISH.getCommandRunner();
File passwordFile = new File("password-file.txt");
CommandResult result = commandRunner.run("create-file-user",
"--passwordfile", passwordFile.getAbsolutePath(),
"--groups", "user",
USERNAME
);
}
I was getting the same error and have managed to work around it, although my situation is slightly different. I'm starting GF 3.1.2 from the "maven-embedded-glassfish-plugin" maven plugin, but this might work for you as well.
Try setting the following system property:
java.security.auth.login.config=target/test-classes/login.conf
This should point to a copy of the login.conf file. You can find this file in the "config" folder in any Glassfish domain folder.
I'm trying to use Azure storage locally. I have a data source class called ExpenseDataSource:
public class ExpenseDataSource
{
private static CloudStorageAccount storageAccount;
private ExpenseTableContext context;
static ExpenseDataSource()
{
//CloudStorageAccount.SetConfigurationSettingPublisher(
// (configName, configSettingPublisher) =>
// {
// string connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
// configSettingPublisher(connectionString);
// }
//);
storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
CloudTableClient.CreateTablesFromModel(typeof(ExpenseTableContext), storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
}
public ExpenseDataSource()
{
context = new ExpenseTableContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));
}
public IEnumerable<ExpenseInfo> Select()
{
var results = from g in context.Expenses
where g.PartitionKey == "Expense"
select g;
return results;
}
// ...
}
(I'm new to Azure, so this class could be sub-optimal in many ways.)
When I try to create an object of type ExpenseDataSource, the following exception occurs:
System.TypeInitializationException: The type initializer for 'WebRole1.ExpenseDataSource' threw an exception. ---> System.InvalidOperationException: SetConfigurationSettingPublisher needs to be called before FromConfigurationSetting can be used
at Microsoft.WindowsAzure.CloudStorageAccount.FromConfigurationSetting(String settingName)
at WebRole1.ExpenseDataSource..cctor() in [ ... ]
--- End of inner exception stack trace ---
at WebRole1.ExpenseDataSource..ctor()
at WebRole1.ExpenseService.WebRole1.IExpenseService.GetExpenses() in [ ... ]
However, this is odd, because SetConfiguationSettingPublisher has already been called:
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
DiagnosticMonitor.Start("DiagnosticsConnectionString");
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
RoleEnvironment.Changing += RoleEnvironmentChanging;
CloudStorageAccount.SetConfigurationSettingPublisher(
(configName, configSettingPublisher) =>
{
string connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
configSettingPublisher(connectionString);
}
);
return base.OnStart();
}
// ...
}
I am able to hit breakpoints here when I start debugging.
What am I doing wrong here?
Update: I thought that maybe I'd started the dev fabric and ASP.NET localhost out of order, so I killed them both, launched the dev fabic, then launched the ASP project. Still no luck - the same error occurs.
Update 2: I changed my OnStart() to this, but it still doesn't work:
public override bool OnStart()
{
DiagnosticMonitor.Start("DiagnosticsConnectionString");
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
RoleEnvironment.Changing += RoleEnvironmentChanging;
#region Setup CloudStorageAccount Configuration Setting Publisher
// This code sets up a handler to update CloudStorageAccount instances when their corresponding
// configuration settings change in the service configuration file.
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
// Provide the configSetter with the initial value
configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
RoleEnvironment.Changed += (sender, arg) =>
{
if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
.Any((change) => (change.ConfigurationSettingName == configName)))
{
// The corresponding configuration setting has changed, propagate the value
if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
{
// In this case, the change to the storage account credentials in the
// service configuration is significant enough that the role needs to be
// recycled in order to use the latest settings. (for example, the
// endpoint has changed)
RoleEnvironment.RequestRecycle();
}
}
};
});
#endregion
return base.OnStart();
}
Update 3: I tried putting the "Setup CloudStorageAccount Configuration Setting Publisher" region in the ExpenseDataSource static initializer, and got the following error:
System.TypeInitializationException: The type initializer for 'WebRole1.ExpenseDataSource' threw an exception. ---> System.Runtime.InteropServices.SEHException: External component has thrown an exception.
at RoleEnvironmentGetConfigurationSettingValueW(UInt16* , UInt16* , UInt32 , UInt32* )
at Microsoft.WindowsAzure.ServiceRuntime.Internal.InteropRoleManager.GetConfigurationSetting(String name, String& ret)
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(String configurationSettingName)
at WebRole1.ExpenseDataSource.<.cctor>b__0(String configName, Func`2 configSetter) in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseDataSource.cs:line 26
at Microsoft.WindowsAzure.CloudStorageAccount.StorageAccountConfigurationSetting..ctor(String configurationSettingName)
at Microsoft.WindowsAzure.CloudStorageAccount.FromConfigurationSetting(String settingName)
at WebRole1.ExpenseDataSource..cctor() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseDataSource.cs:line 47
--- End of inner exception stack trace ---
at WebRole1.ExpenseDataSource..ctor()
at WebRole1.ExpenseService.WebRole1.IExpenseService.GetExpenses() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseService.svc.cs:line 18
Update 3: Following smarx's suggestion, I changed the static initializer:
static ExpenseDataSource()
{
//storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudTableClient.CreateTablesFromModel(typeof(ExpenseTableContext), storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
}
This leads to the following error:
System.TypeInitializationException: The type initializer for 'WebRole1.ExpenseDataSource' threw an exception. ---> System.Runtime.InteropServices.SEHException: External component has thrown an exception.
at RoleEnvironmentGetConfigurationSettingValueW(UInt16* , UInt16* , UInt32 , UInt32* )
at Microsoft.WindowsAzure.ServiceRuntime.Internal.InteropRoleManager.GetConfigurationSetting(String name, String& ret)
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(String configurationSettingName)
at WebRole1.ExpenseDataSource..cctor() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseDataSource.cs:line 20
--- End of inner exception stack trace ---
at WebRole1.ExpenseDataSource..ctor()
at WebRole1.ExpenseService.WebRole1.IExpenseService.GetExpenses() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseService.svc.cs:line 18
The error is slightly different from above. Could this be related to the idea that I'm somehow not actually running ASP.NET within the dev fabric?
Ugh. I'm starting to miss Google App Engine storage's simple get() and put() interface.
1) Make sure that "DataConnectionString" is configured in your settings of WebRole.
In your Solution Explorer --> Under the "Roles" folder --> Right-click on | Properties --> Go to Settings tab and click "Add Setting". Enter Name: "DataConnectionString"; Type:"ConnectionString"; Value:"UseDevelopmentStorage=true" (if you want to debug and use local storage) or if you are planning to migrate to Azure-enter your storage account details.
2) (In the above code - Remove the comment for SetConfigurationSettingPublisher). Your code should look like this:
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
});
var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
I can think of two reasons:
You are using Azure SDK 1.3 and the SetConfigurationSettingPublisher must be called in your Global.asax.cs Application_Start;
You are not setting the Startup project as the *.CloudService one.
If you're still having problems, try actually selecting the Web Role under the Cloud Project and starting debugging from there, that has worked for me when I've had issues with other methods.
Had the same problem, I didn't had the Azure project as start-up project.
As Muhammad Omar mention in his comment on the question, see this related question as well.