Database connection error in Selenium - mysql

I've written a class which fetcheS data from the databasE:
#Test
void ts() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/selenium","root","root");
Statement stm=con.createStatement();
ResultSet rs=stm.executeQuery("select * from seleniumusers");
while(rs.next()){
name=rs.getString("firstname");
System.out.println(name);
e(mysql)
But on running the test from testng once the browser gets open it gives and error:
Warning: mysql_pconnect() [function.mysql-pconnect]: Can't connect to MySQL server on 'localhost' (10061) in C:\Program Files\vtigercrm-5.2.1\apache\htdocs\vtigerCRM\adodb\drivers\adodb-mysql.inc.php on line 373

public WebDriverWait wait;
String filename;
File file;
Workbook RegExcel = null;
Row row = null;
Sheet RegExcelSheet = null;
FileInputStream inputStream;
public String[][] excelDataValue;
public int rowCount;
public List<WebElement> AllRegularization=null;;
String projectPath = System.getProperty("user.dir");
#Given("^User Save Excel At Said Location$")
public void user_save_excel_at_said_location() throws Throwable {
filename="RegDates.xlsx";
file = new File (projectPath +"\\"+ filename);
}
#When("^Excel File Is Readable$")
public void excel_file_is_readable() throws Throwable {
inputStream = new FileInputStream(file);
String fileExtensionName = filename.substring(filename.indexOf("."));
}
#Then("^Read The Excel$")
public void read_the_excel() throws Throwable {
RegExcel = new XSSFWorkbook(inputStream);
RegExcelSheet = RegExcel.getSheet("Sheet1");
}
#And("^Create Array For Dates Data In Excel$")
public void create_array_for_dates_data_in_excel() throws Throwable {
rowCount = RegExcelSheet.getLastRowNum()-RegExcelSheet.getFirstRowNum();
excelDataValue = new String[rowCount+1][5];
for (int i = 0; i < rowCount+1; i++)
{
row = RegExcelSheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++)
{
excelDataValue[i][j]=row.getCell(j).toString();
//System.out.println(row.getCell(j).toString());
}
}
}

Related

trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc

NetworkUtilities.java
public class NetworkUtilities {
private static final String TAG = NetworkUtilities.class.getSimpleName();
public static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
}catch (MalformedURLException e){
Log.v(TAG, "Problem building the Url");
}
return url;
}
public static String httpRequest(URL url) throws IOException{
String jsonResponse = "";
if(url ==null){
Log.v(TAG, "Url is null");
return jsonResponse;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200){
inputStream = httpURLConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
else{
Log.e(TAG, "Error response code" + httpURLConnection.getResponseCode());
}
}catch (IOException e){
Log.v(TAG, "Problem retrieving the json result", e);
}finally {
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
if(inputStream != null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader in = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bf = new BufferedReader(in);
String line = bf.readLine();
while(line != null){
output.append(line);
line = bf.readLine();
}
}
return output.toString();
}
public static List<String> extractFromJson(String jsonResponse){
if(TextUtils.isEmpty(jsonResponse)){
return null;
}
List<String> newsStories = new ArrayList<>();
try{
JSONObject baseObj = new JSONObject(jsonResponse);
JSONArray articlesArray = baseObj.getJSONArray("data");
for(int i=0;i<articlesArray.length();i++){
JSONObject currentArticle = articlesArray.getJSONObject(i);
JSONObject source = currentArticle.getJSONObject("source");
String sourceName = source.getString("name");
String title = currentArticle.getString("title");
String description = currentArticle.getString("description");
String newsStory = "Source" + sourceName + "/n" + title + "/n" + description;
newsStories.add(newsStory);
}
}catch (JSONException e){
Log.e(TAG, " Problem parsing the json string", e);
}
return newsStories;
}
NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context mContext;
private List<String> mNewsArticles;
NewsAdapter(Context context){
mContext = context;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(mContext)
.inflate(R.layout.news_list_item,parent, false);
view.setFocusable(true);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder( NewsViewHolder holder, int position) {
String currentArticle = mNewsArticles.get(position);
holder.mTextView.setText(currentArticle);
}
#Override
public int getItemCount() {
if(mNewsArticles != null){
return mNewsArticles.size();
}
return 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position :" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
}
public void setNewsData(List<String> newsData){
mNewsArticles = newsData;
notifyDataSetChanged();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private NewsAdapter mNewsAdapter;
private static final String BASE_URL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=13f428d687714c33a24f34ad6c5***87";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
mNewsAdapter = new NewsAdapter(this);
mRecyclerView.setAdapter(mNewsAdapter);
new FetchNewsArticle().execute(BASE_URL);
}
public class FetchNewsArticle extends AsyncTask<String, Void, List<String>>{
#Override
protected List<String> doInBackground(String... strings) {
String stringUrl = strings[0];
URL url = NetworkUtilities.createUrl(stringUrl);
String json = "";
try{
json = NetworkUtilities.httpRequest(url);
List<String> articles = NetworkUtilities.extractFromJson(json);
return articles;
}catch (Exception e){
e.printStackTrace();
Log.v(TAG, "Problem retrieving data");
return null;
}
}
#Override
protected void onPostExecute(List<String> strings) {
if(strings != null){
mNewsAdapter.setNewsData(strings);
}
}
}
Error
W/Zygote: Unable to open libbeluga.so: dlopen failed: library "libbeluga.so" not found.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/xample.newsfee: Accessing hidden method Landroid/view/View; >computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.newsfee: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
com.example.newsfeed V/NetworkUtilities: Problem retrieving the json result
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:46)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
2021-03-11 22:53:28.124 9391-9391/com.example.newsfeed W/Looper: PerfMonitor looperActivity : package=com.example.newsfeed/.MainActivity time=1ms latency=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running=212ms runnable=80ms io=11ms late=91ms h=android.app.ActivityThread$H w=159)
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM build : 979eaa0, I11632bc865
Build Date : 11/18/20
OpenGL ES Shader Compiler Version: EV031.32.02.00
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R1.11.00.00.604.067
Remote Branch : NONE
Reconstruct Branch : NOTHING
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Build Config : S P 10.0.6 AArch64
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
2021-03-11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: fail to open file: No such file or directory
The error seems to be: java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted.
Starting from Android 9, clear text http communication is disabled by default.
Check out the official Android documentation for this and also this question for further information.

migrating encrypted data to Sql server from MYSQL server

We have aes-256 encryption for some data in one of the tables and we are migrating this to sql server. The problem is that we cannot decrypt the data in sql server due to incompatibility. Is there any way we can encrypt data in MYSQL in a way which is compatible with sql server aswell. Any advise ?
if you know the secretkey then you can decrypt the data see following code for encryption and decryption of AES-256 . the code is written in JAVA
check this link AES-256 Password Based Encryption/Decryption in Java
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
private static SecretKey secretKey;
public static void main(String []args) throws Exception {
salt = getSalt();
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}

Quasar multi fibers warning

I am new to quasar and I tried doing this.
Basically I get a warning the fiber is blocking a thread. Why ? can I not do something like below ?
Thanks
//in my my testclass I have this
String websites[] = {"http://www.google.com",""http://www.lol.com",""http://www.somenoneexistantwebsite.com"};
for(int i=0; i < websites.length ; i++){
TestApp.getWebsiteHTML(websites[i]);
}
//in TestApp
public static void getWebsiteHTML(String webURL) throws IOException, InterruptedException, Exception {
new Fiber<Void>(new SuspendableRunnable() {
#Override
public void run() throws SuspendExecution, InterruptedException {
WebInfo mywi = new WebInfo();
mywi.getHTML(webURL);
}
}).start().join();
}
//in WebInfo
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Have a look at the "Runaway fibers" sub-section in the docs.
HttpURLConnection is thread-blocking so in order to avoid stealing threads from the fiber scheduler for too much time (which risks killing your Quasar-based application's performance) you should rather use an HTTP client integrated with Quasar (or integrate one yourself).

Getting a MAC address from the IP's retrieved from a ping sweep

Basically I have 2 bits of code one will do a ping sweep of a network range and then one will retrieve a MAC address from a given IP.
What I would like to do is incorporate these two pieces of code so when the ping sweep is performed it shows the MAC address in the output next to the IP addresses.
The MAC address retrieval code is as follows...
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test118;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test118 {
public static String command;
public String ip = "192.168.0.4";
Test118() {
command = "arp -a " + ip;
}
public void viewMac() {
String process = null;
String mac[] = new String[5];
String rmac[] = new String[10];
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
int i = 0;
while ((line = bufferedreader.readLine()) != null) {
mac[i] = line;
i++;
}
rmac = mac[3].split(" ");
System.out.println(rmac[2]);
} catch (Exception e) {
System.out.println("mac cant find");
}
}
public static void main(String[] args) throws Exception {
Test118 r = new Test118();
r.viewMac();
}
}
The ping sweep is as follows...
package pingstestnew;
import java.io.IOException;
import java.net.InetAddress;
public class NetworkPing {
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 142; i <= 145; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
System.out.println(address + " Host is reachable");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " Hostname Resolved, Host is reachable");
}
else
{
System.out.println(address + " Host Unreachable");
}
}
}
}

I want to know, why get a exception of redis.clients.jedis.exceptions.JedisConnectionException?

I used jedis in my java project with one master and slave, once the slave started, it come to this in redis_slave.log:
44764 [2721] 24 Dec 14:07:41.157 * Connecting to MASTER...
44765 [2721] 24 Dec 14:07:41.158 * MASTER <-> SLAVE sync started
44766 [2721] 24 Dec 14:07:41.158 # Error condition on socket for SYNC: Connection refused
and in my java source file, I want to delete all data in redis, so I wrote this code:
public class TestJedisPool {
private Jedis jedis = null;
private JedisPool jedisPool = null;
public TestJedisPool() {
initialPool();
jedis = jedisPool.getResource();
jedis.auth("123456");
}
private void initialPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(20);
config.setMaxIdle(5);
config.setMaxWait(1000L);
config.setTestOnBorrow(false);
jedisPool = new JedisPool(config, "192.168.144.3", 6397);
}
private void masterThread() {
System.out.println(jedis.flushAll());
jedisPool.returnResource(jedis);
jedis.disconnect();
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestJedisPool test = new TestJedisPool();
test.masterThread();
}
}
and get a exception like this:
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:22)
at com.oppo.testpool.TestJedisPool.<init>(TestJedisPool.java:15)
at com.oppo.testpool.TestJedisPool.main(TestJedisPool.java:41)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
any one can help me ?
I modified your code and it works for:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
public class TestJedisPool {
static ExecutorService executor = Executors.newSingleThreadExecutor();
final static ShardedJedisPool redisStatsPool;
static {
String host = "127.0.0.1";
int port = 6379;
List<JedisShardInfo> redisClickShard = new ArrayList<JedisShardInfo>();
redisClickShard.add(new JedisShardInfo(host, port));
JedisPoolConfig config = new JedisPoolConfig();
config.maxActive = 1000;
config.maxIdle = 10;
config.minIdle = 1;
config.maxWait = 30000;
config.numTestsPerEvictionRun = 3;
config.testOnBorrow = true;
config.testOnReturn = true;
config.testWhileIdle = true;
config.timeBetweenEvictionRunsMillis = 30000;
redisStatsPool = new ShardedJedisPool( config, redisClickShard);
}
public TestJedisPool() {
}
String[] getRandomNumber(int min, int max){
String[] test = new String[8];
for (int i = 0; i < test.length; i++) {
int partition = min + (int)(Math.random() * ((max - min) + 1));
test[i] = "key"+partition;
}
return test;
}
static volatile long sum = 0;
public Runnable hincrBy(final String keyname, final String[] keyfields , final long val){
Runnable job = new Runnable() {
#Override
public void run() {
c++;
System.out.println(c);
try {
ShardedJedis shardedJedis = redisStatsPool.getResource();
final Jedis jedis = shardedJedis.getShard("") ;
Pipeline p = jedis.pipelined();
for (String keyfield : keyfields) {
p.hincrBy(keyname, keyfield, val);
sum += val;
}
p.sync();
redisStatsPool.returnResource(shardedJedis);
} catch (Exception e) {
//e.printStackTrace();
}
}
};
return job;
}
static volatile int c = 0;
static final int MAX = (int) Math.pow(10, 6);
void masterThread() {
for (int i = 0; i < MAX; i++) {
String[] keynames = getRandomNumber(100, 1000);
executor.submit(hincrBy("test10^6", keynames, 1L));
}
executor.shutdown();
while(!executor.isTerminated()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int sumTest() {
int total = 0;
try {
ShardedJedis shardedJedis = redisStatsPool.getResource();
final Jedis jedis = shardedJedis.getShard("") ;
Map<String,String> map = jedis.hgetAll("test10^6");
Set<String> keys = map.keySet();
for (String keyfield : keys) {
int v = Integer.parseInt(map.get(keyfield));
total += v;
}
redisStatsPool.returnResource(shardedJedis);
} catch (Exception e) {
//e.printStackTrace();
}
return total;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestJedisPool test = new TestJedisPool();
test.masterThread();
System.out.println(sum);
System.out.println(test.sumTest());
System.out.println(test.sumTest() == sum);
}
}