String to FileInputSteam - java

FileInputStream serviceAccount =
new FileInputStream("push-manager-app/src/main/resources/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://test1-use.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
The above code for Firebase connector is working fine. But in openshift environment I can't commit serviceAccountKey.json in resources as it will be different for different environments. I can get it as String from openshift configmap in each environment.
For running this block of code I need to convert String in FileInputStream. I'm not sure how to do it. I have one workaround where I can read String, generate file and use it. But I wanted to use the right way. I checked Firebase API for other options but it can't even handle InputStream.

String json = "xxxxxx";
InputStream stream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));

private static InputStream getFile() {
return FireBaseService.class.getResourceAsStream("/dataCred.json");
}
private static final String DATABASE_URL = "DATABASE_URL";
public static void initiainzeSDK() {
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(getFile()))
.setDatabaseUrl(DATABASE_URL)
.build();
FirebaseApp.initializeApp(options);
// Initialize the default app
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
make sure ur json file not wrong syntax

Related

Why do I get NullPointerException when trying to access resource file?

I want to make so a file in the program is packaged in the jar file because it is needed in my program. It is the firebase credentials file. I read that I need to add it to the resource folder but now I cannot access it because I get NullPointerException. I think the path is valid and everything seems okay but I get null every time. Here is the code:
ClassLoader classLoader = EmailSender.class.getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource("/parkingsystem-cf164-firebase-adminsdk-5jjuk-2be72bfcce.json")).getFile());
And here is the code structure:
code structure
If there is another method to add file to jar I am open to hear it, it is just what I found on the Internet but it does not work for me. Any help is appreciated!
Edit: So apparently it works when the / is removed but then I need to convert it to FileInputStream and there I get FileNotFoundExcpetion. The rest of the code:
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
} catch (IOException e) {
e.printStackTrace();
}

Github java api

I am using org.kohsuke.github java api, and I am trying to create a new subdirectories in an existing Directory in my git repo. Everytime I run my code, I get the same exception:
org.kohsuke.github.GHFileNotFoundException:
{"message":"Not Found",
"documentation_url":"https://developer.github.com/enterprise/2.13/
v3/git/trees/#create-a-tree"}
at org.kohsuke.github.Requester.handleApiError(Requester.java:699)
at org.kohsuke.github.Requester._to(Requester.java:306)
at org.kohsuke.github.Requester.to(Requester.java:247)
at org.kohsuke.github.GHTreeBuilder.create(GHTreeBuilder.java:88)
at GitTest.main(GitTest.java:50)
This is my code:
OkHttpClient okHttpClient = new OkHttpClient();
repository = initGithub(okHttpClient);
GHTree test = getTree();
System.out.println(test.getUrl());
System.out.println(test.getSha());
GHTreeBuilder builder = repository.createTree();
try {
builder.baseTree(test.getSha()).entry("SUB", "040000", "tree",
test.getSha(), null).create();
} catch (IOException e) {
e.printStackTrace();
}
I have tested with different params for the.entry() method. Did anybody use this api before? I don't know what I am doing wrong.

Java Properties Class

using java 8, tomcat 8
Hi, i am loading a file using properties, but i have a check before loading which returns the same properties object if its already been loaded (not null). which is a normal case scenario but i want to know if there is any way that if any change occur in target file, and some trigger should be called and refreshes all the properties objects. here is my code.
public static String loadConnectionFile(String keyname) {
String message = "";
getMessageFromConnectionFile();
if (propertiesForConnection.containsKey(keyname))
message = propertiesForConnection.getProperty(keyname);
return message;
}
public static synchronized void getMessageFromConnectionFile() {
if (propertiesForConnection == null) {
FileInputStream fileInput = null;
try {
File file = new File(Constants.GET_CONNECTION_FILE_PATH);
fileInput = new FileInputStream(file);
Reader reader = new InputStreamReader(fileInput, "UTF-8");
propertiesForConnection = new Properties();
propertiesForConnection.load(reader);
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
} finally {
try {
fileInput.close();
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
}
}
}
}
the loadConnectionFile method executes first and calls getMessageFromConnectionFile which has check implemented for "null", now if we remove that check it will definitely load updated file every time but it will slower the performance. i want an alternate way.
hope i explained my question.
thanks in advance.
Java has a file watcher service. It is an API. You can "listen" for changes in files and directories. So you can listen for changes to your properties file, or the directory in which your properties file is located. The Java Tutorials on Oracle's OTN Web site has a section on the watcher service.
Good Luck,
Avi.

Firebase Admin SDk not working from backend Java

I am trying to push message in firebase real time database through firebase admin sdk java, but my problem is that the same code works
fine on my local system and I am able to push message successfully
in database but its not working in testing environment and testing
environment is AWS server with ubuntu installed in
it, on researching it on google I am not able to find solution for
this?
public static class User {
public String date_of_birth;
public String full_name;
public String nickname;
public User(String date_of_birth, String full_name) {
// ...
}
public User(String date_of_birth, String full_name, String nickname) {
// ...
}
}
Map<String, User> users = new HashMap<>();
users.put("alanisawesome", new User("June 23, 1912", "Alan Turing"));
users.put("gracehop", new User("December 9, 1906", "Grace Hopper"));
Code for making connection is.....
FileInputStream serviceAccount;
FirebaseOptions options;
try {
serviceAccount = new FileInputStream("/********.json");
options = new FirebaseOptions.Builder()
.setDatabaseUrl("https://myDatabaseUrl")
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
FirebaseApp.initializeApp(options);
flagForConnectionWithFirebase=true;
LOGGER.info("Options are:: "+options);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final FirebaseDatabase database =
FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(url);
String key=ref.push().getKey();
ref.child(key).setValueAsync(users);
After a long search I found that the server was not sync with centralised time zone. post doing that code run successfully on testing environment as well.
I found what seems to be quite a common problem that nobody cares to resolve and it is that there an dependency conflict in one of the Firebase dependencies
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
It can be solved by excluding the dependency from Spring Boot Test and the pring-boot-configuration-processor. Now I am having some problems when running test, still cannot tell if they are related.

PayPal REST API java sdk - custom config file

Good afternoon all!
I use PayPal REST API java sdk and I want to have different configurations for different environments of my application. Here is how I'm trying to do so:
private static boolean IS_PRODUCTION = false;
private static String PAYPAL_ACCESS_TOKEN;
private static void initPayPal() {
InputStream is = null;
try {
is = ApplicationConfig.class.getResourceAsStream(
IS_PRODUCTION? "/my_paypal_sdk_config.properties" : "/my_paypal_sdk_config_test.properties");
PayPalResource.initConfig(is);
String clientID = ConfigManager.getInstance().getConfigurationMap().get("clientID");
String clientSecret = ConfigManager.getInstance().getConfigurationMap().get("clientSecret");
PAYPAL_ACCESS_TOKEN = new OAuthTokenCredential(clientID, clientSecret).getAccessToken();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
and while trying to get the clientID I have
java.io.IOException: Resource 'sdk_config.properties' could not be found
Strange behavior - I thought I've just configured the sdk to use my own properties file.
Please advice how could I set up those settings properly!
So here is the solution I found:
Create an empty sdk_config.properties file in default location
Load your own properties:
private static void initPayPal() {
InputStream is = null;
try {
is = ApplicationConfig.class.getResourceAsStream(
IS_PRODUCTION ? "/my_paypal_sdk_config.properties" : "/my_paypal_sdk_config_test.properties");
Properties props = new Properties();
props.load(is);
PayPalResource.initConfig(props);
ConfigManager.getInstance().load(props);
String clientID = ConfigManager.getInstance().getConfigurationMap().get("clientID");
String clientSecret = ConfigManager.getInstance().getConfigurationMap().get("clientSecret");
PAYPAL_ACCESS_TOKEN = new OAuthTokenCredential(clientID, clientSecret).getAccessToken();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
We have made some good improvements to the PayPal Java SDK on integration steps. We are removing the need for sdk_config.properties file as they do not work as well, specially for multi-configuration settings.
Now, all you do is create an APIContext instance with clientId, clientSecret, and mode. You pass that context object for any API operation from there on.
Here is how the code would look like for different configurations:
APIContext defaultContext = new APIContext(clientId1, clientSecret1, "sandbox");
APIContext sandboxContext = new APIContext(clientId2, clientSecret2, "sandbox");
APIContext someOtherContext = new APIContext(clientId3, clientSecret3, "live");
APIContext liveContext = new APIContext(clientId, clientSecret, "live");
// Now pass any of the above context in these calls, and it would use those configurations.
Payment payment = new Payment();
// Fill in all the details.
payment.create(defaultContext);
// Replace that defaultContext with any of those other contexts.
Here is the wiki page explaining that: https://github.com/paypal/PayPal-Java-SDK/wiki/Making-First-Call
I had the same error with SDK 0.11 version. I use my own properties file, but code still looked for "sdk_config.properties". I put it into root in my CLASSPATH, but still got the same error. Then I made obvious and horrible solution: put empty "sdk_config.properties" into "rest-api-sdk-0.11.0.jar" library. This street magic solved my problem.

Categories