Google Cloud Vision crashes without exception caught - google-cloud-vision

I recently encountering an annoying bug that only happen in 1 out of our 3 environments (Amazon EC2 to be specific). When I send a request to the Cloud API to receive tags about the picture. The function crashes but I don't see any exception caught by the try catch. The function works fine until June 1st but I don't know why it doesn't anymore (other 2 environments work just fine).
Here are the code:
try {
GoogleCredentials cred = GoogleCredentials.fromStream(new FileInputStream(coreConfig.googleCreds()));
log.error("GoogleCredentials cred = GoogleCredentials.fromStream(new FileInputStream(coreConfig.googleCreds()));");
ImageAnnotatorSettings imageAnnotatorSettings = ImageAnnotatorSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(cred))
.build();
ImageAnnotatorClient vision = ImageAnnotatorClient.create(imageAnnotatorSettings);
log.error("ImageAnnotatorClient vision = ImageAnnotatorClient.create(imageAnnotatorSettings);");
byte[] data = IOUtils.toByteArray(is);
ByteString bs = ByteString.copyFrom(data);
// Builds the image annotation request
List<AnnotateImageRequest> requests = new ArrayList<>();
log.error("ByteString bs = ByteString.copyFrom(data);");
Image img = Image.newBuilder().setContent(bs).build();
log.error(" Image img = Image.newBuilder().setContent(bs).build();");
Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
log.error("Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();");
AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
.addFeatures(feat)
.setImage(img)
.build();
requests.add(request);
log.error("requests.add(request);");
// Performs label detection on the image file
BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
log.error("BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);");
List<AnnotateImageResponse> responses = response.getResponsesList();
log.error("List<AnnotateImageResponse> responses = response.getResponsesList();");
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
throw new ServiceException(ServiceStatus.BAD_REQUEST, res.getError().getMessage());
}
for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
tags.append("===" + annotation.getDescription().replaceAll("\\s+",""));
log.error("tags.append(\"===\" + annotation.getDescription().replaceAll(\"\\\\s+\",\"\"));");
}
}
return tags;
}catch(Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return null;
// throw new ServiceException(ServiceStatus.BAD_REQUEST, e.getMessage());
}
Here are the details about it:

It seems like an old version of guava (in this case 17.0-jdk) caused this crash.
You still have to remove the old version not only from the pom.xml but also in the lib folder of the .war file.

Related

send notification from background worker

am using ABP to build my project
I have a module to generate big size files using background worker, and after each successful file generated I need to send notification, but is not working !
I've put the background job in the core project and the queue in the engine project,
the DB notification tables are updated successfully (new record inserted so the pull notification will work fine !), but the browser doesn't receive the notification (so I can inform him that his file is ready), but there is no errors and no any notification send to the browser.
here is the worker class:
public class GeneratedFileWorker : BackgroundWorkerBase, ISingletonDependency
{
.
.
.
[UnitOfWork]
[AutomaticRetry(Attempts = 0)]
public override async System.Threading.Tasks.Task ExecuteAsync()
{
var notificationData = new NotificationData();
notificationData["URL"] = "app/main/data/generatedfiles";
using (AbpSession.Use(TenantConsts.DefaultTenantId, TenantConsts.UserServiceId))
{
GetDownloadArticleInput getDownloadArticleInput = new GetDownloadArticleInput();
if (pendingRequest is not null)
{
var entityType = _lookupItemManager.Get(pendingRequest.EntityTypeId).Code;
dynamic Args = JsonConvert.DeserializeObject<GetDownloadArticleInput>(String.Empty);
switch (entityType)
{
case "Article":
Args = JsonConvert.DeserializeObject<GetDownloadArticleInput>(pendingRequest.ExtensionData);
break;
case "ArticlesList":
Args = JsonConvert.DeserializeObject<GetDownloadArticlesInput>(pendingRequest.ExtensionData);
break;
};
GeneratedFile generatedFileDto = new GeneratedFile();
try
{
generatedFileDto = await _generateFile.Generate(Args);
await _appNotifier.SendMessageAsync(new UserIdentifier(1, pendingRequest.CreatorUserId.Value),string.Format(_LocalizationSource.GetString("GeneratedFile.fileIsNotready"), _lookupItemManager.GetTitle(pendingRequest.EntityTypeId)), notificationData, NotificationSeverity.Error);
else
await _appNotifier.SendMessageAsync(new UserIdentifier(1, pendingRequest.CreatorUserId.Value), string.Format(_LocalizationSource.GetString("GeneratedFile.fileIsready"), _lookupItemManager.GetTitle(pendingRequest.EntityTypeId)), notificationData, NotificationSeverity.Success);
}
catch (Exception ex)
{
pendingRequest.CurrentStateId = _lookupItemManager.GetByCode(LookupCategories.GeneratedFileStatus, "Failed").Id;
pendingRequest.OperationResult = ex.ToString();
await _generatedFileRepository.UpdateAsync(pendingRequest);
await _appNotifier.SendMessageAsync(new UserIdentifier(1, pendingRequest.CreatorUserId.Value), string.Format(_LocalizationSource.GetString("GeneratedFile.fileIsNotready"), _lookupItemManager.GetTitle(pendingRequest.EntityTypeId)), notificationData, NotificationSeverity.Error);
}
}
}
}
I have 2 cases here:
first one working when I define the queue in the host project, and
second one not working when I define the queue in the engine project

Android 10 - unable to take PersistableUriPermission on a file that I created in getExternalFilesDir()

Using the below code snippet, we created a file in Android 10, in a sub-folder under getExternalFilesDir(). However, immediately after creation, if we try to take persistableUriPermission, it throws an exception "No such permission exists....".
We need that check to know if that file will be available for read later in a common utility, else we have to make a copy. Please let us know what we might be doing wrong and how to fix this. Appreciate your help.
ParcelFileDescriptor filePFD =
cxt.getContentResolver().openFileDescriptor(Uri.parse(pathFileToSend), "r");
FileDescriptor fd = filePFD.getFileDescriptor();
FileInputStream fIn = new FileInputStream(fd);
File fileBaseFolder = new File(Utils.GetRootDirectory().getAbsolutePath(), Utils.DESTINATION);
if (!fileBaseFolder.exists())
fileBaseFolder.mkdirs();
if (fileBaseFolder.exists()) {
File copyFile = new File(fileBaseFolder.getAbsolutePath(), nameOfFile);
FileOutputStream fOut = new FileOutputStream(copyFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = fIn.read(data)) != -1) {
total += count;
fOut.write(data, 0, count);
}
fOut.close();
Uri copiedFileUri =
FileProvider.getUriForFile(cxt,
cxt.getString(R.string.file_provider_authority),
copyFile);
if (null != copiedFileUri)
{
try {
/*At this line, an exception is thrown - No persistable permissions exist.. */
cxt.getContentResolver().takePersistableUriPermission(copiedFileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
} catch (Exception e) {
e.printStackTrace();
}
}
takePersistableUriPermission() is for Uri values that you get from the Storage Access Framework (e.g., ACTION_OPEN_DOCUMENT). It will not work for FileProvider. And, you do not need permissions to work with getExternalFilesDir() on Android 4.4 and higher.

Haxe - SQLLite Crashing in Android target

i want to use use Sqllite datbase in my Android Game i am developing with Haxe - OpenFl but the app keep crashing when i am trying to query the database. If this is not possible or have any other ways to deal with data in Android kindly let me know as the json and shared objects are not going to work with in my scenario.
i posted this question in the OpenFl community too - but i think it is more related to Haxe then OpenFL.
OpenFl Community Post
What i am doing :
Making a database using DB Browser and saving it to the assets/data/db/data.db
then when app starts i am making a copy of it to the lime.system.System.applicationStorageDirectory
it creates the file in the applicationStorageDirectory
Then i try to connect to the newly created db file and it just connects but right after connecting to it, try to get the name of the db it is connected to
trace("Connected to database " +_conn.dbName ); and it is not showing anything in the trace except the text connected to database.
Ignoring the name i tried to query the Database and it just closes my app without any error or anything i get to know what goes wrong.
My Project.xml
<android target-sdk-version="26" install-location="preferExternal" if="android" />
<android permission="android.permission.WRITE_EXTERNAL_STORAGE"/>
<android permission="android.permission.WRITE_INTERNAL_STORAGE"/>
<haxelib name="openfl" />
<haxelib name="hxcpp" />
<assets path="assets/data/db" rename="db" />
DBClass
package;
import haxe.io.Bytes;
import lime.Assets;
import openfl.system.System;
import sys.FileSystem;
import sys.db.Connection;
import sys.db.Sqlite;
import sys.io.File;
#if android
// Make SQLite work on android by statically compiling the library
import hxcpp.StaticSqlite;
#end
/**
* ...
* #author Sim
*/
class DBManager
{
private var CLONE:String = "db/asset_database.db";
private var NEW:String = "new_db.db";
private var _conn:Connection = null;
public function new()
{
}
public function openDatabase():Void
{
trace("CREATING FILE");
trace("targetPath: " +lime.system.System.applicationStorageDirectory);
//trace("targetPath: " +lime.system.System.applicationDirectory); //Crashing the app
trace("targetPath: " +lime.system.System.documentsDirectory);
trace("targetPath: " +lime.system.System.desktopDirectory);
var targetPath: String = lime.system.System.applicationStorageDirectory+ NEW;
trace("targetPath " + targetPath);
trace("FileSystem.exists(targetPath) " + FileSystem.exists(targetPath));
//Debugging
/*var bytes:Bytes = Assets.getBytes(CLONE);
trace("bytes are here "+bytes);
var content:String = bytes.toString();
trace("content "+content);
File.saveContent(targetPath, content);
trace("Saved");*/
//uncomment when done with errors
/*if (FileSystem.exists(targetPath) == false)
{
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
}*/
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
trace("Saved");
try
{
_conn = Sqlite.open(targetPath+NEW);
}
catch (e:Dynamic)
{
trace("Connection failed with error: "+e);
}
if (_conn != null)
{
trace("Connected to database " +_conn.dbName );
//not getting any database name trying to query
// and KaBoom app gone :D XD
var result = _conn.request("SELECT * FROM TEST");
trace("Query Result "+result.results());
//if i comment then it will go and close the connection too
//without breaking anything O_O
_conn.close();
}
}
}
I took a nap and got the fix in my dreams: :D
The problem is here
_conn = Sqlite.open(targetPath+NEW);
Fix:
_conn = Sqlite.open(targetPath);
Because database name is already in the path :P
var targetPath: String = lime.system.System.applicationStorageDirectory+ NEW;
That’s why always sleep for 8 hours otherwise will end up like me

How to post Special character tweet using asp.net API?

I m using Given below code to post the tweet on twitter. But when we upload it on the server then special character (!,:,$ etc) tweets not published on twitter. this code is working fine in the local system
string key = "";
string secret = "";
string token="";
string tokenSecret="";
try
{
string localFilename = HttpContext.Current.Server.MapPath("../images/").ToString();
using (WebClient client = new WebClient())
{
client.DownloadFile(imagePath, localFilename);
}
var service = new TweetSharp.TwitterService(key, secret);
service.AuthenticateWith(token, tokenSecret);
// Tweet wtih image
if (imagePath.Length > 0)
{
using (var stream = new FileStream(localFilename, FileMode.Open))
{
var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = message,
Images = new Dictionary<string, Stream> { { "name", stream } }
});
}
}
else // just message
{
var result = service.SendTweet(new SendTweetOptions
{
Status = HttpUtility.UrlEncode(message)
});
}
}
catch (Exception ex)
{
throw ex;
}
The statuses/update_with_media API endpoint is actually deprecated by Twitter and shouldn't be used (https://dev.twitter.com/rest/reference/post/statuses/update_with_media).
TweetSharp also has some issues with using this method when the tweet contains both a 'special character' AND an image (works fine with either, but not both). I don't know why and I haven't been able to fix it, it's something to do with the OAuth signature I'm pretty sure.
As a solution I suggest you use TweetMoaSharp (a fork of TweetSharp). It has been updated to support the new Twitter API's for handling media in tweets, and it will work in this situation if you use the new stuff.
Basically you upload each media item using a new UploadMedia method, and that will return you a 'media id'. You then use the normal 'SendTweet' method and provide a list of the media ids to it along with the other status details. Twitter will attach the media to the tweet when it is posted, and it will work when there are both special characters and images.
In addition to TweetMoaSharp you can use Tweetinvi with the following code:
var binary = File.ReadAllBytes(#"C:\videos\image.jpg");
var media = Upload.UploadMedia(binary);
var tweet = Tweet.PublishTweet("hello", new PublishTweetOptionalParameters
{
Medias = {media}
});

how can we store a html page into sqlite in blackberry on memory card / phone memory?

Below code specifies that we we can make http connection in blackberry and how to store html page as a string?
I am doing this but I am able to get that http request but when I get response i.e http_ok it is not correct so that I can save text oh html as a string and I can further store that into sqlite.
LabelField title = new LabelField("SQLite Create Database Sample",
LabelField.ELLIPSIS |
LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Creating a database."));
argURL="https://www.google.com:80";
try {
connDesc = connFact.getConnection(argURL);
if (connDesc != null) {
httpConn = (HttpConnection) connDesc.getConnection();
// //Send Data on this connection
// httpConn.setRequestMethod(HttpConnection.GET);
// //Server Response
StringBuffer strBuffer = new StringBuffer();
inStream = httpConn.openInputStream();
int chr;
int retResponseCode = httpConn.getResponseCode();
if (retResponseCode == HttpConnection.HTTP_OK) {
if (inStream != null) {
while ((chr = inStream.read()) != -1) {
strBuffer.append((char) chr);
}
serverResponceStr = strBuffer.toString();
// appLe.alertForms.get_userWaitAlertForm().append("\n"+serverResponceStr);
//returnCode = gprsConstants.retCodeSuccess;
}
} else {
//returnCode = gprsConstants.retCodeNOK;
}
}
} catch (Exception excp) {
//returnCode = gprsConstants.retCodeDisconn;
excp.printStackTrace();
} `enter code here`
The code does not perform any database functionality, however I tested and it does successfully perform an HttpRequest to an external URL. The data that comes back is based on the response of the server you are making the request to.
The code I used can be found here:
http://snipt.org/vrl7
The only modifications is to keep a running summary of various events, and the response is displayed in the RichTextField. Basically, this looks to be working as intended, and the resulting String should be able to be saved however you see fit; though you may need to be cautious of encoding when saving to a database so that special characters are not lost or misinterpreted.

Resources