Search This Blog

Monday, February 29, 2016

basic linux command

find a keyword

grep -rnw 'path'  -e "pattern"

find  . -name "name of file"

Friday, February 26, 2016

Find website load times with simple java code

import java.net.*;
import java.io.*;

public class TimerTest
{
    public static final Double NANO_TO_MILLIS = 1000000.0;
    public static void main(String[] args) throws MalformedURLException, IOException
    {
    int i =0;
    while(i<5){
        // start timer
        long nanoStart = System.nanoTime();
        long milliStart = System.currentTimeMillis();

        // do work to be timed
        doWork();

        // stop timer
        long nanoEnd = System.nanoTime();
        long milliEnd = System.currentTimeMillis();

        // report response times
        long nanoTime = nanoEnd - nanoStart;
        long milliTime = milliEnd - milliStart;
        reportResponseTimes(nanoTime, milliTime);
        i++;
    }
    }

    private static void reportResponseTimes(long nanoTime, long milliTime)
    {
        // convert nanoseconds to milliseconds and display both times with three digits of precision (microsecond)
        String nanoFormatted = String.format("%,.3f", nanoTime / NANO_TO_MILLIS);
        String milliFormatted = String.format("%,.3f", milliTime / 1.0 );

        //System.out.println("Milliseconds using nanoTime(): " + nanoFormatted);
        System.out.println("Milliseconds using currentTimeMillis: " + milliFormatted);
    }

    private static void doWork() throws MalformedURLException, IOException
    {
        URL url = new URL("http://google.com");
        URLConnection conn = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        System.out.println("Checking "+url.toString());
       
        while (in.readLine() != null) {
        //System.out.println(in.readLine());
        }
        in.close();
    }
}

Monday, February 22, 2016

Grep linux

To find a string in various files on the system.

grep -rnw './path' -e 'pattern'

to search in current file

grep "string" filename

to find cpu

cat /proc/cpuinfo

To find memory

cat /proc/meminfo

Saturday, February 13, 2016

codeigniter .htaccess file working

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L] 

Mysql command line import



go to /bin/mysql.exe -u username -ppassword dbname < "c:\user\import.sql"



no space after -p 

Wednesday, February 10, 2016

Monitor Weblogic via JMX code

Enable JMX via java options in setDomainenv.cmd/sh   located in your user_projects/domain/your_domain/bin/

Go to last and find out JAVA_OPTIONS

Append the JMX parameters to the options

set JAVA_OPTIONS=%JAVA_OPTIONS% -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8888 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false

Restart the server run this java code , this will monitor memory,threads and deadlocks on your weblogic server and add it to an alert file. You can add SMTP details to get an email in case the thresh hold is reached.

/*
 * 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.
 */


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.HashMap;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.openmbean.CompositeData;
import javax.management.remote.*;

/**
 *
 * @author AB839805
 */
public class JMXCron {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, MalformedObjectNameException  {
   BufferedWriter writer =null;
        String host ="your server ip",threadState = "";
int port = 8888;
HashMap map = new HashMap();
boolean deadLockFound = false;
String[] credentials = new String[2];
credentials[0] = "username";
credentials[1] = "password";
map.put("jmx.remote.credentials", credentials);
JMXConnector c = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
c.connect();

ObjectName runtimeService = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.runtime.RuntimeServiceMBean");

//ObjectName sr = (ObjectName) c.getMBeanServerConnection().getAttribute(runtimeService,"ServerRuntime");
//ThreadPoolRuntimeMBean threadPoolRuntimeMBean = runtimeService.getThreadPoolRuntime();
//ObjectName[] managedServers = (ObjectName[])c.getMBeanServerConnection().getAttribute(runtimeService, "ServerRuntimes");
 //String threadCount = (String) c.getMBeanServerConnection().getAttribute(
   //             new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), "ThreadCount").toString();
 
 ThreadMXBean thMxB = ManagementFactory.getThreadMXBean();
 long [] runningThreads = thMxB.getAllThreadIds();


 for( int i =0;i<runningThreads.length;i++){
     threadState += thMxB.getThreadInfo(runningThreads[i]).getThreadState().toString()+"/";
    }
  System.out.println("thread state "+threadState);

 if(thMxB.findDeadlockedThreads()!=null)
 deadLockFound = true;

 System.out.println("thread count"+thMxB.getThreadCount());

//weblogic.health.HealthState tpHealthState = (weblogic.health.HealthState) connection.getAttribute(serverTP, "HealthState");

Object oM = c.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage");
Object oT = c.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=Threading"), "ThreadCount");


CompositeData cd = (CompositeData) oM;
Long used = (Long) cd.get("used");
 Long max = (Long) cd.get("max");
Long percentage = ((used * 100) / max);

System.out.println("Percentage of memory used  "+percentage + "%" );

if(percentage>10 ){
   
   //writer = new PrintWriter("d:\\alert.log", "UTF-8");
   writer = new BufferedWriter(new FileWriter("d:\\alert.log ", true));
writer.newLine();
writer.append("Percentage of memory used  "+percentage + "% "+(new Date())+"\n Thread Count "+runningThreads.length+" Thread State "+threadState);
writer.close();
}
if(deadLockFound ){
   
   //writer = new PrintWriter("d:\\alert.log", "UTF-8");
   writer = new BufferedWriter(new FileWriter("d:\\alert.log", true));
writer.newLine();
writer.append("Dead Lock Found at "+(new Date()));
writer.close();
}

    }
    private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException
{
    return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
}
   
}
///////////////


It will output like 
run:
thread state TIMED_WAITING/TIMED_WAITING/TIMED_WAITING/TIMED_WAITING/RUNNABLE/RUNNABLE/WAITING/WAITING/RUNNABLE/
thread count9
Percentage of memory used  30%




In case you want to automate , run it as a cron.

Make a shell file and give chmod+x yourshell file 

contents of shell file 
//

#!/bin/bash
cd /your path where java file is located 
java JMXCron  // name of your java file 


now go to crontab -e on unix and edit the cron tab file so that you can schedule this JMX cron to run at a scheduled time.

To run this Memory/Thread/Deadlock analysis on weblogic every minute.

////////////

* * * * * //jmx.sh  /Monitoring/cron.log


It will give the log output to cron.log and will generate a cumulative memory report.







Thursday, February 4, 2016

Run TestNg with selenium for load testing and generate Reports from ATU framework

package testng;

import java.util.Date;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import atu.testng.reports.ATUReports;
import atu.testng.reports.listeners.ATUReportsListener;
import atu.testng.reports.listeners.ConfigurationListener;
import atu.testng.reports.listeners.MethodListener;
import atu.testng.reports.logging.LogAs;
import atu.testng.reports.utils.Directory;
import atu.testng.reports.utils.Platform;

@Listeners({ ATUReportsListener.class, ConfigurationListener.class,
MethodListener.class })
public class Scale {


public Scale(){
System.setProperty("atu.reporter.config", "E:\\atu.properties");
}

// constructor for report parameters

public Scale(String reportName ){

ATUReports.indexPageDescription = reportName;
}
 

 
  @Test(invocationCount = 10 ,threadPoolSize =10)
public void loadTestThisWebsite() {

 HtmlUnitDriver unitDriver = new HtmlUnitDriver();
 unitDriver.setJavascriptEnabled(true);
 unitDriver.get("http://localhost/PT");
 WebElement button = unitDriver.findElement(By.name("submit"));
 button.click();
 String title = (String) unitDriver.executeScript("return document.title");
 System.out.println("Tittle  is " + title);
 if("Welcome".equals(unitDriver.getTitle()))
 {
 ATUReports.add("Load time", "PASS", true);
// Thread.sleep(2000);
 String currentDate = (new Date()).toString();
ATUReports.currentRunDescription= currentDate;
        System.out.println("Report Name "+Directory.RUNDir);
 }

 else
 Assert.fail("I have thrown Exception");

 unitDriver.quit();

}
  /*
  @AfterMethod
  public void getRunTime(ITestResult tr) {
      long time = tr.getEndMillis() - tr.getStartMillis();
      System.out.println("Time taken for the request "+ time+" millisec");
  }
 
  */

}

Run TestNG programmatically from Eclipse


Make sure your testng.xml is in some folder and it is used as shown below.


package initialize;

import java.util.ArrayList;
import java.util.List;

import org.testng.TestListenerAdapter;
import org.testng.TestNG;

public class test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
 TestNG testng = new TestNG();
 
   TestListenerAdapter tla = new TestListenerAdapter();
   List<String> testFilesList = new ArrayList<String>();
   testFilesList.add(".\\resources\\testng.xml");
   System.out.println(System.getProperty("user.dir"));
testng.setTestSuites(testFilesList); //you can addd multiple suites either here by adding multiple files or include all suites needed in the testng.xml file
       testng.setUseDefaultListeners(false);
       testng.addListener(tla);
       testng.run();
}

}