JCE cannot authenticate the provider BC in Robolectric - robolectric

I am trying to test a keystore signing in my app, but cannot pass over loading a keystore from the assets, because the error is thrown:
java.io.IOException: error constructing MAC:
java.lang.SecurityException: JCE cannot authenticate the provider BC
here is the code
#Test
public void testKeyStore() {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream inputStream = RuntimeEnvironment.application.getAssets().open(fileName);
keyStore.load(inputStream, password.toCharArray());
} catch (Exception e) {
e.printStackTrace();
}
}
If not with Robolectric, does anybody has an idea how to run this test?
Thanks

You really don't need Robolectric here. Try next:
#Test
public void testKeyStore() throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
String path = System.getProperty("user.dir") + "src/main/assets/filename.key";
InputStream inputStream = TimerTest.class.getResourceAsStream(path);
keyStore.load(inputStream, "test".toCharArray());
}

Related

Error sending media group: [400] Bad Request: wrong remote file identifier specified: Wrong string length

I'm building a Java telegram bot, and one of the features is to send a group of photos from local.
However, when executing the bot, it fails to upload the photos with error message:
org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException:
Error sending media group: [400] Bad Request: wrong remote file identifier specified: Wrong string length
at org.telegram.telegrambots.meta.api.methods.send.SendMediaGroup.deserializeResponse(SendMediaGroup.java:86)
I'm using 'org.telegram:telegrambots:5.7.1' by the way: https://github.com/rubenlagus/TelegramBots
My code
#Slf4j
#AllArgsConstructor
public class GetPhotosCommand implements BotCommand {
private Bot bot;
#Override
public void execute(Update update) {
final String chatId = String.valueOf(update.getMessage().getChatId());
List<InputMedia> inputMediaList = new ArrayList<>();
InputMediaPhoto inputMediaPhoto1 = InputMediaPhoto.builder()
.caption("cat photos")
.media("1")
.mediaName("001")
.isNewMedia(true)
.newMediaFile(new File("~/Desktop/001.png"))
.build();
InputMediaPhoto inputMediaPhoto2 = InputMediaPhoto.builder()
.media("2")
.mediaName("002")
.isNewMedia(true)
.newMediaFile(new File("~/Desktop/002.png"))
.build();
inputMediaList.add(inputMediaPhoto1);
inputMediaList.add(inputMediaPhoto2);
SendMediaGroup sendMediaGroup = SendMediaGroup.builder()
.chatId(chatId)
.medias(inputMediaList)
.protectContent(true)
.build();
SendMessage sendMessage = SendMessage.builder()
.chatId(chatId)
.text("Hello, here are my cats.")
.build();
try {
bot.execute(sendMediaGroup);
bot.execute(sendMessage);
} catch (TelegramApiException e) {
log.error("Exception is thrown: {}", e);
}
}
}

ERROR_UNKNOWN downloading file from Firebase Storage

Im trying to download a file *.Apk from the storage and install when is completed.
i revised the rules from storage and the uses.
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read : if request.auth.uid != null;
}
}
}
on rules monitor all operations are accepted but the file can't be donwloaded
fragment of donwload code is:
public void downloadUpdate() {
StorageReference gsReference = FirebaseStorage.getInstance("filename.apk");
final String rutadestino = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
final String nombrearchivo = "LeaderBoard-Upd.apk";
final Uri archivodestino = Uri.parse("file://" + rutadestino+nombrearchivo);
File localFile = new File(rutadestino+nombrearchivo);
if (localFile.exists()) {
localFile.delete();
}
gsReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Local temp file has been created
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", new File(rutadestino+nombrearchivo));
Intent install = new Intent(Intent.ACTION_VIEW);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setData(contentUri);
startActivity(install);
//unregisterReceiver(this);
finish();
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(archivodestino,
"application/vnd.android.package-archive");
startActivity(install);
//unregisterReceiver(this);
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
int errorCode = ((StorageException) exception).getErrorCode();
String errorMessage = exception.getMessage();
Emergente.ErrorCode(1,getApplicationContext());
}
});
}
i received
errorcode "13000"
errorMessage "An unknown error occurred, please check the HTTP result code and inner exception for server response."
cause "open failed: EACCES (Permission denied)"
Maybe another code fragment is wrong, but in this momment im stucked on the OnFailureListener
The problem is on the app permissions, when app tries to download files and write it on a wrong directory/file without the required permission it will trow the "ERROR_UNKNOWN" message.
The solution is create the file on the same app directory, when doing so the permission is not required unles the API <= 18 then the permission will be necessary.
Solution:
File localFile = new File(getExternalFilesDir(null), "file.apk");

Calling java object/class from java servlet

I have created a dynamic web project in eclipse.
It contains a Servlet ResidentApi.java and two java classes:GeoLocationDemo.java and Geolocation.java. I am calling GeoLocationDemo.java from my servlet and getting result in a ResultSet.But i am not getting any value in ResultSet.
When i ran same GeoLocationDemo.java separatly i am getting right results.I don't know servlet is able to call my java class or not but if it is then why i am not getting results.
I am having hard time debugging it.What i am doing is running .war file of this project every time on tomcat server and checking results there.Please suggest a good method to test it on eclipse.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ResultSet rs = null;
try{
GeoLocationDemo geo = new GeoLocationDemo(); //Here i created a new object
rs = geo.getResults(); //here i called a method of GeoLocation
}catch(Exception e){
// System.out.println(e);
out.write("<head><b You suck</b></head>");
}
out.write("<head><b>Congratulation! connected</b></head>"); //i am getting this output
try{
while(rs.next()){
String s = rs.getString("Details");
out.write("<head><b> "+s+ " </b></head>"); //not able to get this output
}
}catch(Exception e){
// System.out.println(e);
out.write("<head><b>You Built </b></head>");
}
out.close();
}
Don't put everything in a <head> tag! Open a body somewhere. Don't silently swallow any Exception you might be getting. Do remember to close() the ResultSet. Also, you should probably be returning all of your data in a List with a POJO.
out.write("<body>");
out.write("<b>Congratulation! connected</b><br/>");
try {
while (rs.next()) {
String s = rs.getString("Details");
out.write("<b> "+s+ "</b><br/>");
}
} catch (Exception e){
// System.out.println(e);
out.write("<b>" + e.getMessage() + "</b>");
e.printStackTrace(out);
} finally {
try {
out.close();
} catch (Exception ignored) {
}
try {
rs.close();
} catch (Exception ignored) {
}
}
configure remote debugging between your IDE and Tomcat server e.g. take a look on Remote debugging Tomcat with Eclipse
localize the problem - is the problem in GeoLocationDemo or in ResultSet or in output processing
p.s. do not close resources you never open - out.close(); - it is managed by servlet container

can't storing and retrieving images and files into database in spring mvc with MyEclipse IDE

I m doing a real time project using spring mvc with MyEclipse IDE without integrating maven, and my question is how to store and retrieve images and files into database.
Controller code for storing an image file in a database:
#RequestMapping(value = "/saveproduct")
public ModelAndView add(#ModelAttribute("command") CommonBean cbean,
BindingResult result, HttpServletRequest request) throws Exception {
CommonsMultipartFile file = cbean.getImage();
System.out.println("file content is " + file);
cbean.setFile(file.getBytes());
ProductModel model = new ProductModel();
try {
BeanUtils.copyProperties(model, cbean);
eworldservice.addproduct(model);
} catch(Exception ex) {
ex.printStackTrace();
}
return new ModelAndView("home");
}

Android : Linkedin request token failed

I have used the linkedin-j-android.jar of version 1.0.429 in my android project
here is the link for downloading patched linkedin-j-android.jar with scope fix
http://db.tt/yQjhqeq3
below is the code which i have used in my project:
class ShowNetWorkUtils{
public static final String CONSUMER_KEY = "xxxxx";
public static final String CONSUMER_SECRET = "yyyy";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "calback";
public String scopeParams="rw_nus+r_baseprofile";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME
+ "://" + OAUTH_CALLBACK_HOST;
private void configureLinkedIn() {
new Thread(){
#Override
public void run() {
try {
Looper.prepare();
LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService (CONSUMER_KEY,CONSUMER_SECRET,scopeParams);
LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(CONSUMER_KEY,CONSUMER_SECRET);
LinkedInRequestToken liToken = oauthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
//LinkedInRequestToken liToken = oauthService.getOAuthRequestToken();
String url = liToken.getAuthorizationUrl();
/* For Linkedin dialog create and show */
LKDialog lkdDialog = new LKDialog(_context, url);
LKDialog lkdDialog.setDelegate(ShowNetWorkUtils.this);
LKDialog lkdDialog.show();
Looper.loop();
}
catch (Exception e) {
e.printStackTrace();
}
} //End run
}.start();
}
} //End Class
I am getting the exception when i request for the token in line "oauthService.getOAuthRequestToken(OAUTH_CALLBACK_URL)" and also i have used "oauthService.getOAuthRequestToken()" but i am getting the same exception in this case also.
The exception is :
com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceException: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: https://api.linkedin.com/uas/oauth/requestToken?scope=rw_nus+r_baseprofile
please provide me some solution to solve this..
Replace the following line in your code
public String scopeParams="rw_nus+r_baseprofile";
with
public String scopeParams="rw_nus+r_basicprofile";
Because the permission scope is r_basicprofile but you have written as r_baseprofile
Hope it will help you.

Resources