Storage.put(key, file, {
resumable: true,
completeCallback(eve) {
},
errorCallback: (err) => {
console.error('Unexpected error while uploading', err);
},
progressCallback(prog) {
}
});
I want to handle this error but cannot find anyway to do that
xhr.js?b50d:187 PUT https://xyz.amazonaws.com/&x-id=UploadPart net::ERR_NETWORK_CHANGED
[ERROR] 59:15.420 axios-http-handler - Network Error
Related
I have an app where I am using a custom authentication method. First, on the user login into the app, I generate the JWT Token on the server and send it back to the app.
function generateJWT($con,$userID,$cretedTime) {
$secret_Key = "-----BEGIN PRIVATE KEY-----\HCPW\nAtY9K1/19yScEhdmhw8Ozek=\n-----END PRIVATE KEY-----\n";
$date = time();
//$expire_at = $date->modify('+3 minutes')->getTimestamp(); // Add 60 seconds
$domainName = "firebase-adminsdk-XXXXXXXX.iam.gserviceaccount.com";
$request_data = [
'iss' => $domainName,
'sub' => $domainName,
'aud' => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
'iat' => $date, // Issued at: time when the token was generated
// Issuer
//'exp' => $date+(60*60), // Maximum expiration time six month in seconds //15778476
'uid' => $userID, // User name
'created' => $cretedTime, // User name
];
$newToken = JWT::encode($request_data,$secret_Key,'RS256');
return $newToken;
}
Then In the app send on receiving this token I am start the login process.my app using custom firebase auth
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCustomToken(Session.getJWT())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isComplete()){
if(getActivity()!=null){
//User Logged In Successfully
}else{
// Failed
}
}
}
});
So after days of googling, I got the Firebase rules for the structure of my database to look like this
{
"Chat": {
"206-4": "",
"311-158": "",
"215-112": "",
"734-115": "",
"734-55": "",
"734-468": "",
"34-32": "",
"534-179": "",
"734-345": {
"-NI7hqW3YTFKpnSZU422": {
"Message": "Test",
"Message_From": "Support ",
"Message_From_ID": "4",
"Message_To": "Demo",
},
"-NMVOwlAqmyIA52QU9F-": {
"Message": "Hi",
"Message_From": "Support ",
"Message_From_ID": "4",
"Message_To": "Demo",
}
},
"347-234": {
"-NI7hXybU02Mg6vYqdKp": {
"Message": "Ohio",
"Message_From": "Elaxer Support ",
"Message_From_ID": "4",
"Message_To": "Demo 2",
}
},
"281-69": "",
"317-34": ""
},
"Users": {
"4": {
"Online": false,
"lastSeen": "1675785660782"
},
"284": {
"Online": false,
"lastSeen": "1673611185873"
}
},
"UsersLocations": {
"4-210": {
"-1": {
"Latitude": "22.605",
"Longitude": "88.375"
}
},
"25-21": {
"-1": {
"Latitude": "22.605",
"Longitude": "88.375"
}
}
}
}
Firebase Rules
{
"rules": {
"Chat": {
"$room_id": {
".read": "auth.uid === $room_id && $room_id.beginsWith(auth.uid + '-') || auth.uid === $room_id && $room_id.endsWith('-' + auth.uid)",
".write": "auth.uid === $room_id && $room_id.beginsWith(auth.uid + '-') || auth.uid === $room_id && $room_id.endsWith('-' + auth.uid)"
}
},
"Users": {
"$uid": {
".write": "$uid === auth.uid"
}
},
"UsersLocations": {
"$user_location_id": {
".read": "auth.uid === $user_location_id && $user_location_id.endsWith('-location')",
".write": "auth.uid === $user_location_id && $user_location_id.endsWith('-location')"
}
}
}
}
So when ever i tried to create or get the Chat node (Chatroom).
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Chat");
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
It gives me error
Listen at /Chat failed: DatabaseError: Permission denied
I am not able to understand why i am getting this error when i am only checking the user id exist in room name and my jwt token on generation time having user id of one user. Please help me out, what's wrong i am doing with my rules
As Alex also answered: you're not granting anyone read access to /Chat, so any code trying to read from there will be rejected. I would not recommend his answer though, as the rule on /Chat makes the more strict rules on /Chat/$room_id meaningless.
I recommend reading the documentation on rules don't filter data (which explains why your current code don't work and on the fact that permissions cascade (which explains why the rules in Alex' answer make the ones you already have meaningless).
The data structure you have look like what I described in my answer to: Best way to manage Chat channels in Firebase. In my answer there I also showed how to model security rules to allow read access and how to get a list of the chat room for the user, so I recommend checking that out.
As I tried explaining in the comments, the way you handle the sign-in result is wrong:
// ❌ THIS IS WRONG ❌
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCustomToken(Session.getJWT())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isComplete()){
if(getActivity()!=null){
//User Logged In Successfully
}else{
// Failed
}
}
}
});
Instead, when a Task completes you should check whether it succeeded or failed, as shown in the documentation on handling tas results. In your case that'd be:
// ✅ Handling success and failure correctly 👍
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCustomToken(Session.getJWT())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()!=null) {
// User signed in
// TODO: access database
} else {
// Sign in failed
throw task.getException();
}
}
});
I am trying to read blockchain event (in Java) using web3j but getting NPE:
java.lang.NullPointerException: null
at org.web3j.protocol.core.filters.LogFilter.process(LogFilter.java:46)
at org.web3j.protocol.core.filters.Filter.getInitialFilterLogs(Filter.java:119)
at org.web3j.protocol.core.filters.Filter.run(Filter.java:69)
at org.web3j.protocol.rx.JsonRpc2_0Rx.run(JsonRpc2_0Rx.java:89)
at org.web3j.protocol.rx.JsonRpc2_0Rx.lambda$ethLogFlowable$2(JsonRpc2_0Rx.java:79)
at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:71)
at io.reactivex.Flowable.subscribe(Flowable.java:14935)
at io.reactivex.Flowable.subscribe(Flowable.java:14872)
at io.reactivex.Flowable.subscribe(Flowable.java:14791)
Code in question
for (EthLog.LogResult logResult : logResults) {
https://github.com/web3j/web3j/blob/master/core/src/main/java/org/web3j/protocol/core/filters/LogFilter.java#L46
#Override
protected void process(List<EthLog.LogResult> logResults) {
for (EthLog.LogResult logResult : logResults) {
if (logResult instanceof EthLog.LogObject) {
Log log = ((EthLog.LogObject) logResult).get();
callback.onEvent(log);
} else {
throw new FilterException(
"Unexpected result type: " + logResult.get() + " required LogObject");
}
}
}
Raised issue https://github.com/web3j/web3j/issues/1486
But as not expected that to be fixed, what should I do?
Sample code and/or code snippets
private void createEventMonitor() {
log.info("createEventMonitor() begin...");
// contract from block
EthFilter filter = new EthFilter(DefaultBlockParameter.valueOf(new BigInteger("7605105")),
DefaultBlockParameterName.LATEST, contractAddress);
//Disposable subscription
subscription = web3j
.ethLogFlowable(filter)
.subscribe(
event -> {
log.info("Withdraw event received:");
log.info(" event data >>> {}", event.getData());
log.info(" event topic >>> {}", event.getTopics().stream().collect(Collectors.joining()));
log.info(" event address >>> {}", event.getAddress());
log.info(" event txHash >>> {}", event.getTransactionHash());
}, error -> {
log.error("Event error: {}", error, error); //!
});
log.info("createEventMonitor() end.");
}
This error should go away in the future after https://github.com/web3j/web3j/pull/1495 solving https://github.com/web3j/web3j/issues/1486 (should be next version after 4.8.7)
In short: JSON RPC error was no visible on web3j level.
To analyze issue like that run program with log level debug to see JSON RPC messages.
As a part of my promote artifact task I am creating a query to send to Artifactory. Unfortunately, it does not work and I am trying to debug it stepwise. Here is the message I am preparing to send. Somehow println returns "check", but does not show anything for message in the logs. Why so?
stage('Promote') {
id = "0.1-2020-01-28-18-08.zip"
try {
message = """
items.find(
{
"$and":[
{ "repo": {"$eq": "generic-dev-local"} },
{ "path": {"$match": "mh/*"} },
{ "name": {"$eq": ${id}}}
]
}
).include("artifact.module.build.number")
"""
println "check"
println message
} catch (e) {
return [''] + e.toString().tokenize('\n')
}
}
I am building a simple prototype based upon the leshan-server-demo included with the repo. I'm attempting to receive updates from objects that have been observed. Packet captures show that the updates are making their way to the server, but I'm receiving no notice of them.
The closest answer I found is from 2015 (How to retrieve updated content on an Observed resource in Leshan?) - but subsequent changes to the Leshan codebase have made the same technique unworkable.
I've tried using the ObservationService to add an ObservationListener, but that only seems to alert me when the Observe has been requested, not when the endpoint sends up changed values.
static private void attachListener(final LeshanServer server) {
System.out.println("Attaching Listener");
server.getObservationService().addListener(new ObservationListener() {
#Override
public void newObservation(Observation observation, Registration registration) {
System.out.println("New Observation");
}
#Override
public void cancelled(Observation observation) {
System.out.println("Observation cancellation");
}
#Override
public void onResponse(Observation observation, Registration registration, ObserveResponse response) {
System.out.println("Observation Response");
}
#Override
public void onError(Observation observation, Registration registration, Exception error) {
System.out.println("Observation Error");
}
});
}
How should I be listening for observed objects on the Leshan server?
You need to handle the onResponse:
From https://github.com/eclipse/leshan/blob/f315c66602b1061175f2441c019b862946d08a55/leshan-server-demo/src/main/java/org/eclipse/leshan/server/demo/servlet/EventServlet.java#L133
#Override
public void onResponse(Observation observation, Registration registration, ObserveResponse response) {
if (LOG.isDebugEnabled()) {
LOG.debug("Received notification from [{}] containing value [{}]", observation.getPath(),
response.getContent().toString());
}
if (registration != null) {
String data = new StringBuilder("{\"ep\":\"").append(registration.getEndpoint()).append("\",\"res\":\"")
.append(observation.getPath().toString()).append("\",\"val\":")
.append(gson.toJson(response.getContent())).append("}").toString();
sendEvent(EVENT_NOTIFICATION, data, registration.getEndpoint());
}
}
The response.getContent() contains the new value. The data json that code builds will look like
{
"ep": "rpitest",
"res": "/3334/0",
"val": {
"id": 0,
"resources": [{
"id": 5704,
"value": 1.7929173707962036
}, {
"id": 5702,
"value": 0.9917597770690918
}, {
"id": 5703,
"value": 154.53704833984375
}]
}
}
If you are using Leshan-server-Demo and if you want to listen to client's notifed value changes from the browser, your frontend side can use eventsource (server sent event) to receive notifications from Leshan-Server Demo.
For example in my angular 7.0 app, I listen to COAP messages changes as below,
// Register Event Source
constructor() {
this.eventsource = new EventSource('server/event?ep=' + this.clientId);
}
// Add listener for COAP messages call back
ngOnInit() {
this.eventsource.addEventListener('COAPLOG', msg => this.coapLogCallback(msg), false);
console.error('Event Source', this.eventsource);
}
// modify coaplogs arrays
coapLogCallback(msg) {
var log = JSON.parse(msg.data);
if (100 < this.coaplogs.length) this.coaplogs.shift();
this.coaplogs.unshift(log);
}
I have done some queries to the database and they usually work but when I am trying to do it in the current class, I get the following error:
{"code":403,"success":false,"message":"Forbidden, No token provided"}
Both classes are too long to post here, and thus I think this is all I can provide:
SET_USER_STAR_COUNT = URL + "setUserProfileStars";
JSONObject request_data=new JSONObject();
try
{
request_data.put("newscore",newStars);
} catch (JSONException e)
{
e.printStackTrace();
}
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.SET_USER_STAR_COUNT, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String user_tag) {
System.out.println("oO" + result);
}
#Override
public void onError(String error, String user_tag)
{}
});
And here is the controller:
Router.post('/setUserProfileStars', function (req, res) {
var username = req.decoded.name;
var newStars = req.decoded.newscore;
var response = [];
var addStars = 'MATCH (n:User) WHERE n.username = "' + username + '" SET n.stars = "'+ newStars +'" RETURN n.stars AS totalStars';
dbneo4j.cypher({
query: addStars
}, function (err, data) {
if (err) {
return res.send({
code: 9325,
message: 'error encountered',
error: err
}).status(9325);
}
response.push(data);
res.send({
code: 200,
message: 'success',
data: response
}).status(200);
});
});
If there is anything else I can provide then I will do so.
The error comes when I try to print the result. My question is why is it doing so and how can I debug and check what is wrong with it?
403 Forbidden indicates that the server is refusing to process your request because you are not authorized. According to the message details, the server expects an authorization token to be passed as a header. You will have to work with the server to determine what "token" it expects.