I am trying to modify this app. But for the first time I have to solve the permission problem which is not happening to me. I have pasted the code and the logcat. Please tell me a solution.
getDeviceId: The user 10214 does not meet the requirements to access
device identifiers
Splah
package com.xitij.spintoearn.Activity;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.facebook.ads.AudienceNetworkAds;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.R;
import com.xitij.spintoearn.Util.Constant;
import com.xitij.spintoearn.Util.Ex;
import com.xitij.spintoearn.Util.Method;
import com.xitij.spintoearn.Util.RestAPI;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class Splash extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 2000;
private Constant constant;
private String GetDeviceID(){
TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String deviceID = null;
int readIMEI= ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE);
if(deviceID == null) {
if (readIMEI == PackageManager.PERMISSION_GRANTED) {
deviceID = tm.getDeviceId().toString();
}
}
return deviceID;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AudienceNetworkAds.initialize(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Constant.DeviceID = GetDeviceID();
login(Constant.DeviceID);
//Toast.makeText(Splash.this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
finish();
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.RECORD_AUDIO)
.check();
constant = new Constant(Splash.this);
Constant.DeviceID = GetDeviceID();
Ex.getIPaddress();
if(Ex.isConnectionEnable(this) && Ex.checkAndRequestPermissions(this,this)){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//login(Constant.DeviceID);
}
},SPLASH_TIME_OUT);
}
}
public void login(final String deviceid) {
String login = RestAPI.API_Device_Login + "&deviceid=" + deviceid;
AsyncHttpClient client = new AsyncHttpClient();
client.get(login, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String success = object.getString("success");
if (success.equals("1")) {
String user_id = object.getString("user_id");
String name = object.getString("name");
String sendEmail = object.getString("email");
String userPhone = object.getString("phone");
String userCode = object.getString("user_code");
constant.sharedEditor.putBoolean(constant.isLogin, true);
constant.sharedEditor.putString(constant.profileId, user_id);
constant.sharedEditor.putString(constant.userName, name);
constant.sharedEditor.putString(constant.userEmail, sendEmail);
constant.sharedEditor.putString(constant.userPhone, userPhone);
constant.sharedEditor.putString(constant.userCode, userCode);
constant.sharedEditor.commit();
LoadSettings();
Constant.user =new User("00",name,sendEmail,"000",userPhone,userCode);
Method.UserLoginLogs(user_id,"Login",Constant.DeviceID);
Intent intent=new Intent(getBaseContext(),MainActivity.class);
startActivity(intent);
finish();
} else {
Intent inst = new Intent(Splash.this, Login.class);
inst.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inst);
finish();
// Ex.okAlertBox(getResources().getString(R.string.login_failed_message));
//Toast.makeText(Login.this, getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Splash.this);
alertDialogBuilder.setTitle("Server Maintenance");
alertDialogBuilder.setMessage("System is Undergoing Maintenance. Please try again later.");
alertDialogBuilder.setPositiveButton(getApplication().getResources().getString(R.string.ok_message),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
public void LoadSettings() {
AsyncHttpClient client = new AsyncHttpClient();
client.get(RestAPI.API_Settings, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response-ls", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String app_name = object.getString("app_name");
String app_logo = object.getString("app_logo");
String app_version = object.getString("app_version");
String app_author = object.getString("app_author");
String app_contact = object.getString("app_contact");
String app_email = object.getString("app_email");
String app_website = object.getString("app_website");
String app_description = object.getString("app_description");
String app_developed_by = object.getString("app_developed_by");
String app_faq = object.getString("app_faq");
String app_privacy_policy = object.getString("app_privacy_policy");
String publisher_id = object.getString("publisher_id");
boolean interstital_ad = Boolean.parseBoolean(object.getString("interstital_ad"));
String interstital_ad_id = object.getString("interstital_ad_id");
String interstital_ad_click = object.getString("interstital_ad_click");
boolean banner_ad = Boolean.parseBoolean(object.getString("banner_ad"));
String banner_ad_id = object.getString("banner_ad_id");
boolean rewarded_video_ads = Boolean.parseBoolean(object.getString("rewarded_video_ads"));
String rewarded_video_ads_id = object.getString("rewarded_video_ads_id");
String redeem_currency = object.getString("redeem_currency");
String redeem_points = object.getString("redeem_points");
String redeem_money = object.getString("redeem_money");
String minimum_redeem_points = object.getString("minimum_redeem_points");
String payment_method1 = object.getString("payment_method1");
String payment_method2 = object.getString("payment_method2");
String payment_method3 = object.getString("payment_method3");
String payment_method4 = object.getString("payment_method4");
String daily_spin_limit = object.getString("daily_spin_limit");
String ads_frequency_limit= object.getString("ads_frequency_limit");
String video_add_point= object.getString("video_add_point");
String app_refer_reward= object.getString("app_refer_reward");
String registration_reward= object.getString("registration_reward");
String video_ads_limit= object.getString("daily_rewarded_video_ads_limits");
Constant.settings = new Settings(app_name, app_logo, app_version, app_author, app_contact, app_email, app_website, app_description, app_developed_by,
app_faq, app_privacy_policy, publisher_id, interstital_ad_id, interstital_ad_click, banner_ad_id, rewarded_video_ads_id, redeem_currency, redeem_points,
redeem_money, minimum_redeem_points, payment_method1, payment_method2, payment_method3, payment_method4, interstital_ad, banner_ad, rewarded_video_ads,daily_spin_limit,ads_frequency_limit,video_add_point,app_refer_reward,registration_reward,video_ads_limit);
Log.d("Response-ls",ads_frequency_limit );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
}
Constant
package com.xitij.spintoearn.Util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import com.xitij.spintoearn.Models.CoinHistory;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.SpinCounter;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.Models.UserBalance;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.reward.RewardedVideoAd;
public class Constant {
public static final String AppSid="spin";
public static final int POINT_VIDEO_MIN=1;
public static final int POINT_VIDEO_MAX=100;
public static final int RATE_POINT=1000;
public static final int DAILY_CHECK=100;
public static String Total_Point;
//Enter milliseconds
public static final int Waitsecond=8000;
public static String PublicIP;
public static String DeviceID;
public static final String ReferPoint = "10";
public static final String VIDEO_AD_ID="ca-app-pub-3940256099942544/8691691433";
public static final String INSTE_AD_ID="ca-app-pub-3940256099942544/1033173712";
public static final String AD_ID= "#";
public static int AD_COUNT = 0;
public static int VIDEO_AD_COUNT= 0;
public static InterstitialAd mInterstitial;
public static RewardedVideoAd mRewardedVideoAd;
public static User user;
public static UserBalance userBalance;
public static CoinHistory coinHistory;
public static Settings settings;
public static SpinCounter spinCounter;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor sharedEditor;
private Activity activity;
private final String loginPerfm = "login";
public String isLogin = "isLogin";
private String deviceId = "deviceId";
public String profileId = "profileId";
public String userEmail = "userEmail";
public String userPassword = "userPassword";
public String userName = "userName";
public String userPhone = "userPhone";
public String userCode = "userCode";
public String Spin_Count = "Spin_Count";
#SuppressLint("CommitPrefEdits")
public Constant(Activity activity) {
this.activity = activity;
sharedPreferences = activity.getSharedPreferences(loginPerfm, 0); // 0 - for private mode
sharedEditor = sharedPreferences.edit();
}
}
logcat
2021-03-08 08:05:02.525 14296-14296/? E/itij.spintoear: Unknown bits set in runtime_flags: 0x8000
2021-03-08 08:05:04.622 14296-14296/com.xitij.spintoearn E/fdsan: attempted to close file descriptor 74, expected to be unowned, actually owned by FILE* 0x76c3b37018
2021-03-08 08:05:04.758 14296-14296/com.xitij.spintoearn E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xitij.spintoearn, PID: 14296
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xitij.spintoearn/com.xitij.spintoearn.Activity.Splash}: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.os.Parcel.createException(Parcel.java:2071)
at android.os.Parcel.readException(Parcel.java:2039)
at android.os.Parcel.readException(Parcel.java:1987)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:10389)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:1620)
at com.xitij.spintoearn.Activity.Splash.GetDeviceID(Splash.java:53)
at com.xitij.spintoearn.Activity.Splash.onCreate(Splash.java:99)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3378)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
I am trying to create a simple utility application but have issues with merging two word documents with images.
Pls find my below code (i am using Apache POI). The code works fine for Text and other information but fails to merge documents with Images.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
public class WordMerge {
private final OutputStream result;
private final List<InputStream> inputs;
private XWPFDocument first;
public WordMerge(OutputStream result) {
this.result = result;
inputs = new ArrayList<>();
}
public void add(InputStream stream) throws Exception{
inputs.add(stream);
OPCPackage srcPackage = OPCPackage.open(stream);
XWPFDocument src1Document = new XWPFDocument(srcPackage);
if(inputs.size() == 1){
first = src1Document;
} else {
CTBody srcBody = src1Document.getDocument().getBody();
first.getDocument().addNewBody().set(srcBody);
}
}
public void doMerge() throws Exception{
first.write(result);
}
public void close() throws Exception{
result.flush();
result.close();
for (InputStream input : inputs) {
input.close();
}
}
public static void main(String[] args) throws Exception {
FileOutputStream faos = new FileOutputStream("C:/temp/result.docx");
WordMerge wm = new WordMerge(faos);
wm.add( new FileInputStream("C:\\temp\\test.docx") );
wm.add( new FileInputStream("C:\\temp\\word_images.docx") );
wm.doMerge();
wm.close();
}
}
I was trying to achieve, Cucumber feature level parallel execution using pico Container.
When I am using a shared Driver in a context Class as below, I get org.picocontainer.PicoCompositionException: Duplicate Keys not allowed. Duplicate
public class Context{
private ThreadLocal<WebDriver> drivers = new ThreadLocal<>();
public void setDriver(WebDriver wd) {
drivers.set(wd);
}
public WebDriver getDriver() {
return drivers.get();
}
//Runner Class
import java.net.MalformedURLException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.CucumberFeatureWrapper;
import cucumber.api.testng.TestNGCucumberRunner;
import net.thumbtack.cucumber.picocontainer.example.step.SharedDriver;
import cucumber.api.testng.*;
#CucumberOptions (glue = {"net.thumbtack.cucumber.picocontainer.example.step"},
features = "src/main/resources/"
,tags = {"#Scenario2,#Scenario3"})
public class TestRunner {
public TestRunner() throws MalformedURLException {
super();
// TODO Auto-generated constructor stub
}
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
System.setProperty("ExecEnv","Docker");
}
// #Test(dataProvider = "features")
// public void feature(PickleEventWrapper eventwrapper,CucumberFeatureWrapper cucumberFeature) throws Throwable {
#Test(groups="cucumber", description="Runs CucumberFeature",dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature){
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
// testNGCucumberRunner.runScenario(eventwrapper.getPickleEvent());
}
#DataProvider(parallel=true)
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
// return testNGCucumberRunner.provideScenarios();
}
#AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}
Using Apache POI to parse text documents and search for keywords inside them
I just simply create resume parser that parse each document(.doc, .docx) to find given keywords in folder or in sub-folder. Please read the Java-Doc of HWPFDocument.
Here is code
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hwpf.HWPFDocument;
public class ResumeParser {
HWPFDocument document;
FileInputStream fileInputStream;
String rootFolderPath;
Map<String, List<String>> displayContent = new HashMap<String, List<String>>();
List<String> keywordList;
public ResumeParser(String rootFolderPath, List<String> keywordList) throws IOException {
this.rootFolderPath = rootFolderPath;
this.keywordList = keywordList;
startParsing();
}
public void startParsing() throws IOException {
createDisplayContent(rootFolderPath);
printContent(displayContent);
}
/**
* Creates the display content it parse the each file under given folder and
* also in sub folder. folder
*
* #param rootFolderPath
* the root folder path
*/
public void createDisplayContent(String rootFolderPath) {
File fileL = new File(rootFolderPath);
File[] fileArrL = fileL.listFiles();
for (int i = 0; i < fileArrL.length; i++) {
File fileTempL = fileArrL[i];
if (fileTempL.isFile()) {
String name = fileTempL.getName();
String extension = name.substring(name.indexOf('.') + 1, name.length()).toUpperCase();
if (extension.equals("DOC") || extension.equals("DOCX")) {
parseDocFile(fileTempL.getAbsolutePath());
}
} else if (fileTempL.isDirectory()) {
createDisplayContent(fileTempL.getAbsolutePath());
}
}
}
public void parseDocFile(String filePath) {
try {
fileInputStream = new FileInputStream(filePath);
document = new HWPFDocument(fileInputStream);
String text = document.getText().toString().toUpperCase();
Iterator<String> iteratorL = keywordList.iterator();
List<String> matchKeywordListL = new ArrayList<String>();
String keywordL = "";
while (iteratorL.hasNext()) {
keywordL = iteratorL.next().toUpperCase();
if (text.contains(keywordL)) {
matchKeywordListL.add(keywordL.toLowerCase());
}
}
displayContent.put(filePath, matchKeywordListL);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void printContent(Map<String, List<String>> displayContent) {
Iterator<String> iteratorL = displayContent.keySet().iterator();
String keyL = "";
while (iteratorL.hasNext()) {
keyL = iteratorL.next();
System.out.println("File Name: " + keyL + " Match Keywords: " + displayContent.get(keyL));
}
}
public static void main(String args[]) throws IOException {
List<String> keywordListL = new ArrayList<String>();
keywordListL.add("Java");
keywordListL.add("PHP");
keywordListL.add("Andriod");
keywordListL.add("John");
new ResumeParser("D:\\Doc", keywordListL);
}
}
I'm trying to run an appium test on a real ios device using java, testng, and log4j. I am not too familiar with log4j. I am getting the following error in eclipse.
org.testng.TestNGException:
An error occurred while instantiating class MobileTests.AppiumIOSTestAppTest1: org.apache.logging.log4j.spi.Provider: Provider org.apache.logging.slf4j.SLF4JProvider not found
package MobileTests;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import org.apache.log4j.Logger;
import Base.TestBase;
import Common.ScreenshotURL;
import Locators.LocatorMethods;
public class AppiumIOSTestAppTest1 extends TestBase{
static SoftAssert softAssert = new SoftAssert();
static Logger log = Logger.getLogger(AppiumIOSTestAppTest1.class);
String className = this.getClass().getSimpleName();
Date date1= new Date();
String originaltimestamp = new Timestamp(date1.getTime()).toString();
String timestamp = originaltimestamp.replace(':', 'x').substring(11);
String foldername = folderpath+className+timestamp;
String error = "";
String errorname = "";
#Test
public void iosTestAppTest1 () throws IOException, InterruptedException
{
try
{
LocatorMethods.clickByXpath(driver, "textfield1.xpath");
LocatorMethods.sendKeysIntoElementByXpath(driver, "textfield1.xpath", Integer.toString(8));
LocatorMethods.clickByXpath(driver, "textfield2.xpath");
LocatorMethods.sendKeysIntoElementByXpath(driver, "textfield2.xpath", Integer.toString(9));
LocatorMethods.clickByXpath(driver, "compute.xpath");
String answer = LocatorMethods.getTextByXpath(driver, "answer.xpath");
try
{
Assert.assertTrue(answer.equalsIgnoreCase(Integer.toString(17)), "Answer is wrong.");
}
catch(AssertionError e)
{
log.debug("Wrong answer was calculated.");
log.error("This is an exception", e);
//error = e.toString();
//System.out.println(error);
errorname = "wronganswer";
ScreenshotURL.screenshotURL(driver, foldername, errorname, error);
softAssert.fail();
}
}
catch(AssertionError e)
{
System.out.println(e);
}
softAssert.assertAll();
}
#AfterMethod
public static void OnFailure(ITestResult testResult) throws IOException {
if (testResult.getStatus() == ITestResult.FAILURE)
{
System.out.println(testResult.getStatus());
}
}
}