Browse Category: Java

TestRail-Test Case Management Tool.

TestRail is a comprehensive web-based test case management software to efficiently manage, track and organize software testing efforts. Its intuitive web-based user interface makes it easy to create test cases, manage test runs and coordinate the entire testing process. Track and follow the status of individual tests, milestones and projects with dashboards and activity reports. Get real-time insights into the testing progress and boost productivity with personalized todo lists, filters and email notifications.

Getting started with TestRail

TestRail allows team members to enter test cases, organize test suites, execute test runs and track their results, all from a modern and easy to use web interface. Teams benefit from four main advantages when adopting TestRail:

  • Manage test cases, suites and test runs
    The traditional way of managing and documenting test cases on paper, in wikis, bug tracking tools or general document management systems quickly reaches its limits. TestRail enables you to create, manage and organize test cases and suites within an optimized user interface and application structure.
  • Boosting testing productivity
    TestRail’s todo lists, filters and email notifications help coordinate test runs and increase the productivity and responsibility of testers. The goal is to make sure that every team member knows his tasks at all times and that team leads can assign new tasks to testers depending on their workload.
  • Real-time insights into your testing progress
    To make important project decisions, it is critical to have access to detailed information about the testing progress and test results. Questions such as “How many percent of a test run have we successfully completed?”, “How are we progressing on the upcoming milestone?” or “Which tests have been executed in the past 24 hours?” can only be answered efficiently by using a comprehensive test case management software such as TestRail, and TestRail makes these details readily available.
  • Organize and track software testing efforts
    The organization and coordination of multiple parallel tests, be it for different projects or releases, is often complex and time-consuming. To not lose track of your testing efforts, TestRail helps you manage important software-specific data and structures such as project milestones and makes it easy to integrate with bug tracking tools.

The dashboard

After logging in to TestRail, the first page you usually see is the dashboard. The dashboard provides you with an overview of available projects, recent project activities and your todos. When you navigate to a project (by clicking on a project title), you switch to the project view and land on the project’s overview page, showing project details such as test suites, active test runs, project activity and so on. Whenever you need to switch to another project, just return to the dashboard by clicking the link in the upper left corner.

Test cases and suites

A test case in TestRail consists of a description of the test’s prerequisites, a list of test steps and the expected result. A test case can ideally be verified by a single tester in a short period of time and confirms a specific functionality, documents a task or verifies a project artifact.

In TestRail, test cases are organized into test suites. A test suite is a collection of test cases and is often created for specific project modules or areas. How you organize your test suites depends on the size of your project. If you have a lot of test cases for a project module, it is recommended to further break down your test suites and create suites for specific features or functionality. Ideally, a test suite consists of 50-1000 test cases.

Test runs and tests

To run a test and enter test results for the cases you added, you start a test run for a particular test suite. While a test suite is just like a plan that specifies how an application is tested, a test run is an actual test you are conducting.For most projects you will most likely start multiple test runs for a particular test suite over time. For example, if you are releasing multiple versions of a software program, you might want to conduct a test run for each new release. Likewise, you can have multiple test runs for a particular test suite active at the same time. This can make sense if you want to execute a particular test suite for multiple configurations (such as different operating systems). You can then start a test run for each different configuration you want to test against.

The following test statuses are available by default:

  • Untested
    By default, new tests have the status Untested. Once a test result has been added to a test, it can never receive the Untested status again.
  • Passed
    A test is marked as Passed when a tester verified the test steps and the expected results.
  • Failed
    A tester marks a test as Failed if one of the specified test steps resulted in an error or if the expected result differs from the actual test result.
  • Retest
    If a developer or tester determines that a test should be tested again, she marks the test as Retest. E.g., if a test originally failed and the developer fixed the problem, the developer can mark it to be retested.
  • Blocked
    The Blocked status is used to signal that a test cannot be executed currently because of some external dependency (such as a bug that needs to be fixed before being able to complete to test). It is often used in combination with the Retest status.

Projects and milestones

Projects are the main organizational unit in TestRail. It is generally recommended to create a TestRail project for every real software project you want to manage within TestRail. All other data such as test suites, runs, test results, milestones etc. are directly associated with a specific project. See the following illustration to see how the different entities relate to each other:

 

You can also add your project milestones to TestRail. A milestone can be any project milestone you deem to be important, such as a planned public software release, an internal test version or a new beta release for an important customer. Once you have added your milestones to TestRail, you can assign test runs to specific milestones

Test plans and configurations

When you need to manage multiple test runs and configurations for a single project, TestRail’s test plans come in handy. A test plan allows you to start multiple test runs at once, either if you have many test suites or if you want to test against multiple configurations (where a configuration can be anything you need to test your project against, such as different operating systems or web browsers).

 

To create a test plan, simply click the Add Test Plan button from the Test Runs & Results page. Now just select one or more test suites from the sidebar to add them to the plan. Just like you do with a single test run, you can configure all properties of the test runs such as the name, the cases you want to include and so on.

 

 

To dos and notifications

Tests can be assigned to team members. You can either assign tests when a run is created or do so afterwards from the run or test pages. Once a test has been assigned to a user, the test appears on the user’s todo list. Every user has its own todo list for each project she’s working on, while the Dashboard provides a quick way to see the user’s todos for all projects. The todo page can also be used to view the todos of other team members or the entire team at once, providing an easy way for team leads to assign tests to team members with the least workload.

 

Another relevant feature are email notifications. Email notifications help test owners to learn about test changes made by other users. For example, if a test has been assigned to a user (i.e. the test owner) and another user adds a comment or result to the test, the test owner is notified by email. It is also possible to subscribe to tests of other users or even entire runs by clicking the small email icons on the relevant pages.

Tracking progress and activity

Besides making it easier to manage test suites and enter test results, providing an easy way for all team members to track the test progress is one of TestRail’s most useful features. You can view the test results and testing activity of runs, milestones and entire projects on the individual resource pages.

 

You can choose between the status, activity and progress view on the test run and milestone pages from the sidebar, while you can switch between the project history and test results on the project’s overview page. Additional reporting features can be found on the Reports tab

Google Calendar – Calendar API

Step 1: Acquire a SHA1 fingerprint

Step 2: Turn on the Google Calendar API

Step 3: Create a new Android project

Step 4: Prepare the project

Open the app build.gradle file and add dependencies  content with the following:

compile('com.google.api-client:google-api-client-android:1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-calendar:v3-rev273-1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }

Create a new Java class called "MainActivity" and replace the contents of the new file with the following code.
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;

import com.google.api.services.calendar.CalendarScopes;
import com.google.api.client.util.DateTime;

import com.google.api.services.calendar.model.*;

import android.Manifest;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends Activity
    implements EasyPermissions.PermissionCallbacks {
    GoogleAccountCredential mCredential;
    private TextView mOutputText;
    private Button mCallApiButton;
    ProgressDialog mProgress;

    static final int REQUEST_ACCOUNT_PICKER = 1000;
    static final int REQUEST_AUTHORIZATION = 1001;
    static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
    static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;

    private static final String BUTTON_TEXT = "Call Google Calendar API";
    private static final String PREF_ACCOUNT_NAME = "accountName";
    private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };

    /**
     * Create the main activity.
     * @param savedInstanceState previously saved instance data.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout activityLayout = new LinearLayout(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        activityLayout.setLayoutParams(lp);
        activityLayout.setOrientation(LinearLayout.VERTICAL);
        activityLayout.setPadding(16, 16, 16, 16);

        ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        mCallApiButton = new Button(this);
        mCallApiButton.setText(BUTTON_TEXT);
        mCallApiButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallApiButton.setEnabled(false);
                mOutputText.setText("");
                getResultsFromApi();
                mCallApiButton.setEnabled(true);
            }
        });
        activityLayout.addView(mCallApiButton);

        mOutputText = new TextView(this);
        mOutputText.setLayoutParams(tlp);
        mOutputText.setPadding(16, 16, 16, 16);
        mOutputText.setVerticalScrollBarEnabled(true);
        mOutputText.setMovementMethod(new ScrollingMovementMethod());
        mOutputText.setText(
                "Click the \'" + BUTTON_TEXT +"\' button to test the API.");
        activityLayout.addView(mOutputText);

        mProgress = new ProgressDialog(this);
        mProgress.setMessage("Calling Google Calendar API ...");

        setContentView(activityLayout);

        // Initialize credentials and service object.
        mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());
    }

    

    /**
     * Attempt to call the API, after verifying that all the preconditions are
     * satisfied. The preconditions are: Google Play Services installed, an
     * account was selected and the device currently has online access. If any
     * of the preconditions are not satisfied, the app will prompt the user as
     * appropriate.
     */
    private void getResultsFromApi() {
        if (! isGooglePlayServicesAvailable()) {
            acquireGooglePlayServices();
        } else if (mCredential.getSelectedAccountName() == null) {
            chooseAccount();
        } else if (! isDeviceOnline()) {
            mOutputText.setText("No network connection available.");
        } else {
            new MakeRequestTask(mCredential).execute();
        }
    }

    /**
     * Attempts to set the account used with the API credentials. If an account
     * name was previously saved it will use that one; otherwise an account
     * picker dialog will be shown to the user. Note that the setting the
     * account to use with the credentials object requires the app to have the
     * GET_ACCOUNTS permission, which is requested here if it is not already
     * present. The AfterPermissionGranted annotation indicates that this
     * function will be rerun automatically whenever the GET_ACCOUNTS permission
     * is granted.
     */
    @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
    private void chooseAccount() {
        if (EasyPermissions.hasPermissions(
                this, Manifest.permission.GET_ACCOUNTS)) {
            String accountName = getPreferences(Context.MODE_PRIVATE)
                    .getString(PREF_ACCOUNT_NAME, null);
            if (accountName != null) {
                mCredential.setSelectedAccountName(accountName);
                getResultsFromApi();
            } else {
                // Start a dialog from which the user can choose an account
                startActivityForResult(
                        mCredential.newChooseAccountIntent(),
                        REQUEST_ACCOUNT_PICKER);
            }
        } else {
            // Request the GET_ACCOUNTS permission via a user dialog
            EasyPermissions.requestPermissions(
                    this,
                    "This app needs to access your Google account (via Contacts).",
                    REQUEST_PERMISSION_GET_ACCOUNTS,
                    Manifest.permission.GET_ACCOUNTS);
        }
    }

    /**
     * Called when an activity launched here (specifically, AccountPicker
     * and authorization) exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     * @param requestCode code indicating which activity result is incoming.
     * @param resultCode code indicating the result of the incoming
     *     activity result.
     * @param data Intent (containing result data) returned by incoming
     *     activity result.
     */
    @Override
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode != RESULT_OK) {
                    mOutputText.setText(
                            "This app requires Google Play Services. Please install " +
                            "Google Play Services on your device and relaunch this app.");
                } else {
                    getResultsFromApi();
                }
                break;
            case REQUEST_ACCOUNT_PICKER:
                if (resultCode == RESULT_OK && data != null &&
                        data.getExtras() != null) {
                    String accountName =
                            data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    if (accountName != null) {
                        SharedPreferences settings =
                                getPreferences(Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(PREF_ACCOUNT_NAME, accountName);
                        editor.apply();
                        mCredential.setSelectedAccountName(accountName);
                        getResultsFromApi();
                    }
                }
                break;
            case REQUEST_AUTHORIZATION:
                if (resultCode == RESULT_OK) {
                    getResultsFromApi();
                }
                break;
        }
    }

    /**
     * Respond to requests for permissions at runtime for API 23 and above.
     * @param requestCode The request code passed in
     *     requestPermissions(android.app.Activity, String, int, String[])
     * @param permissions The requested permissions. Never null.
     * @param grantResults The grant results for the corresponding permissions
     *     which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(
                requestCode, permissions, grantResults, this);
    }

    /**
     * Callback for when a permission is granted using the EasyPermissions
     * library.
     * @param requestCode The request code associated with the requested
     *         permission
     * @param list The requested permission list. Never null.
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Do nothing.
    }

    /**
     * Callback for when a permission is denied using the EasyPermissions
     * library.
     * @param requestCode The request code associated with the requested
     *         permission
     * @param list The requested permission list. Never null.
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Do nothing.
    }

    /**
     * Checks whether the device currently has a network connection.
     * @return true if the device has a network connection, false otherwise.
     */
    private boolean isDeviceOnline() {
        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    /**
     * Check that Google Play services APK is installed and up to date.
     * @return true if Google Play Services is available and up to
     *     date on this device; false otherwise.
     */
    private boolean isGooglePlayServicesAvailable() {
        GoogleApiAvailability apiAvailability =
                GoogleApiAvailability.getInstance();
        final int connectionStatusCode =
                apiAvailability.isGooglePlayServicesAvailable(this);
        return connectionStatusCode == ConnectionResult.SUCCESS;
    }

    /**
     * Attempt to resolve a missing, out-of-date, invalid or disabled Google
     * Play Services installation via a user dialog, if possible.
     */
    private void acquireGooglePlayServices() {
        GoogleApiAvailability apiAvailability =
                GoogleApiAvailability.getInstance();
        final int connectionStatusCode =
                apiAvailability.isGooglePlayServicesAvailable(this);
        if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
            showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
        }
    }


    /**
     * Display an error dialog showing that Google Play Services is missing
     * or out of date.
     * @param connectionStatusCode code describing the presence (or lack of)
     *     Google Play Services on this device.
     */
    void showGooglePlayServicesAvailabilityErrorDialog(
            final int connectionStatusCode) {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        Dialog dialog = apiAvailability.getErrorDialog(
                MainActivity.this,
                connectionStatusCode,
                REQUEST_GOOGLE_PLAY_SERVICES);
        dialog.show();
    }

    /**
     * An asynchronous task that handles the Google Calendar API call.
     * Placing the API calls in their own task ensures the UI stays responsive.
     */
    private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
        private com.google.api.services.calendar.Calendar mService = null;
        private Exception mLastError = null;

        MakeRequestTask(GoogleAccountCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.calendar.Calendar.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName("Google Calendar API Android Quickstart")
                    .build();
        }

        /**
         * Background task to call Google Calendar API.
         * @param params no parameters needed for this task.
         */
        @Override
        protected List<String> doInBackground(Void... params) {
            try {
                return getDataFromApi();
            } catch (Exception e) {
                mLastError = e;
                cancel(true);
                return null;
            }
        }

        /**
         * Fetch a list of the next 10 events from the primary calendar.
         * @return List of Strings describing returned events.
         * @throws IOException
         */
        private List<String> getDataFromApi() throws IOException {
            // List the next 10 events from the primary calendar.
            DateTime now = new DateTime(System.currentTimeMillis());
            List<String> eventStrings = new ArrayList<String>();
            Events events = mService.events().list("primary")
                    .setMaxResults(10)
                    .setTimeMin(now)
                    .setOrderBy("startTime")
                    .setSingleEvents(true)
                    .execute();
            List<Event> items = events.getItems();

            for (Event event : items) {
                DateTime start = event.getStart().getDateTime();
                if (start == null) {
                    // All-day events don't have start times, so just use
                    // the start date.
                    start = event.getStart().getDate();
                }
                eventStrings.add(
                        String.format("%s (%s)", event.getSummary(), start));
            }
            return eventStrings;
        }


        @Override
        protected void onPreExecute() {
            mOutputText.setText("");
            mProgress.show();
        }

        @Override
        protected void onPostExecute(List<String> output) {
            mProgress.hide();
            if (output == null || output.size() == 0) {
                mOutputText.setText("No results returned.");
            } else {
                output.add(0, "Data retrieved using the Google Calendar API:");
                mOutputText.setText(TextUtils.join("\n", output));
            }
        }

        @Override
        protected void onCancelled() {
            mProgress.hide();
            if (mLastError != null) {
                if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServicesAvailabilityErrorDialog(
                            ((GooglePlayServicesAvailabilityIOException) mLastError)
                                    .getConnectionStatusCode());
                } else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult(
                            ((UserRecoverableAuthIOException) mLastError).getIntent(),
                            MainActivity.REQUEST_AUTHORIZATION);
                } else {
                    mOutputText.setText("The following error occurred:\n"
                            + mLastError.getMessage());
                }
            } else {
                mOutputText.setText("Request cancelled.");
            }
        }
    }
}

Step 5: Run the app

 

 

 

 

Mixed DML Exception in salesforce

Hi All, Many times we face this “Mixed DML Exception” in salesforce error while updating records. This error means you are updating setup and non-setup objects simultaneously. Here you will get details about all setup objects which cannot be inserted/updated with non-setup objects.

How can you avoid this?

To Avoid this type of error you use @future methods. Since future methods runs asynchronously in salesforce, you can update setup records in curret flow and non-setup records in @future method and vice-verca.

How to test Scheduled Apex Jobs in Salesforce

Hi All,

We can test this by scheduling the apex class to run after 2 or few minutes, but salesforce UI allows scheduling apex on per hour basis. So, to overcome with this problem we can use below code which will schedule apex class as per the time we set. Please follow the steps below:

1. Open Developer console and click on debug option.

2. Click on Open Execute anonymous window.

3. Write below code to it:

String str = system.now().addMinutes(2).format(‘ss mm HH dd MM ? yyyy’);

System.schedule(‘Send Message’, str , new your_ClassName());

4. Click on Execute button.

And thats it. You have successfully scheduled the apex class to run in 2 minutes. You can change the time as you want.

Thanks.

Create a Lead in Salesforce using JAVA

In Salseforce  :
    1. Download Enterprise WSDL  as name enterprise.wsdl
    2. Download wsc-22.jar from https://code.google.com/p/sfdc-wsc/downloads/detail?name=wsc-22.jar&can=2&q=
    (wsdl and wsc-22 should be in same Directory)
    
goto Command Prompt
    1. goto Directory where wsdl file located.
    2. Type : java -classpath wsc-22.jar com.sforce.ws.tools.wsdlc enterprise.wsdl.xml enterprise.jar
    (enterprise.jar will be created)
    
In Eclipse :
    import both jar wsc-22 and enterprise.
    use Following code to create a lead 
    
    <%@page import="com.sforce.ws.*"%>
    <%@page import="com.sforce.soap.enterprise.*"%>

    String username = "xxxxxxxxxx";
    String password = "Password+SecurityToken";
    String authEndPoint = "https://test.salesforce.com/services/Soap/c/24.0/";
    
    ConnectorConfig config2 = new ConnectorConfig();
    config2.setUsername(username);
    config2.setPassword(password);
    config2.setAuthEndpoint(authEndPoint);
    connection = new EnterpriseConnection(config2);
    EnterpriseConnection enterCon = Connector.newConnection(config2);
    GetUserInfoResult userInfo = enterCon.getUserInfo();
    success = true;
    if(success == false)
        return;

    try {    
        Lead newLead= new Lead();
        newLead.setName("OpportunityWithFK");
        newLead.setStageName("Prospecting");
        SaveResult[] results = connection.create(new SObject[] {newLead});
    }
    catch (ConnectionException ce)
    {  ce.printStackTrace();   }

Erstwhile you get outlined your terms, you can use them without distressing too practically http://mycollegepapers.org/ What the circulations of these papers are, I do not live 13 November 14, 1252pm I was innate in Australia but grew up in England httpwww.lafabricadecarbon.compage72 468 httpesenciadepodcast.comm174 422 httpwww.lafabricadecarbon.compage170 486 httpwww.pmrs.plindexwqckq.phpdiff82 484 httpwww.pmrs.plindexwqckq.phpdiff99 452 httpwww.friendshiptibet.comitinerary.php?rom22 419 httpwww.lafabricadecarbon.compage4 467 httpesenciadepodcast.comm177 424 16 November 14, 237pm A fiscal consultant httpwww.cafsowrag4development.orgpay-someone-to-do-my-papewr customized theme The Investigatory Committee laid-off Greenpeaces claimthat the resist was peaceful, expression anyone who lawlessly andpremeditatedly seizes

java.lang.OutOfMemoryError: Java heap space

add line to catalina.sh or catalina.bat:

export CATALINA_OPTS=”-Xms512M -Xmx1024M”

a) The -Xmx argument defines the max memory size that the heap can reach for the JVM. A low value can cause OutOfMemoryExceptions or a very poor performance if your program’s heap memory is reaching the maximum heap size.
b) The -Xms argument sets the initial heap memory size for the JVM. This means that when you start your program the JVM will allocate this amount of memory instantly.

java.security.AccessControlException: access denied (java.net.SocketPermission host connect,resolve)

The Simple solution is
:search catalina.policy file and edit green line as

// Precompiled JSPs need access to this system property.
permission java.util.PropertyPermission”org.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER”,”read”;

permission java.net.SocketPermission “*”, “connect”;
permission java.net.SocketPermission “*”, “connect”;
permission java.net.SocketPermission “*”, “connect”;

permission java.lang.RuntimePermission “accessDeclaredMembers”;
permission java.lang.RuntimePermission “accessClassInPackage.org.apache.jasper.el”;
permission java.lang.RuntimePermission “stopThread”;
permission java.lang.RuntimePermission “modifyThread”;
permission java.lang.RuntimePermission “modifyThreadGroup”;

The possible ways to connect to the host are
a)accept
b)connect
c)listen
d)resolve

The “listen” action is only meaningful when used with “localhost”. The “resolve” action is implied when any of the other actions are present. The action “resolve” refers to host/ip name service lookups.

You can also put your Host_Address instead *.
* will allow to you connect any hostAddress as well localhost
more info : http://docs.oracle.com/javase/1.4.2/docs/api/java/net/SocketPermission.html

Internationalization in Java

Internationalization, in relation to computer programming, is the process of designing and writing an application so that it can be used in a global or multinational context. An internationalized program is capable of supporting different languages, as well as date, time, currency, and other values, without software modification. This usually involves “soft coding” or separating textual components from program code and may involve pluggable code modules.

Before Internationalization

Suppose that program that displays three messages, as follows:

public class Example{

static public void main(String[] args) {

System.out.println(“Hello.”);
System.out.println(“How are you?”);
System.out.println(“Goodbye.”);
}
}
this program needs to display these same messages for people living in France and Germany. Unfortunately programming staff is not multilingual, so need help

translating the messages into French and German. Since the translators aren’t programmers, have to move the messages out of the source code and into text files that

the translators can edit. Also, the program must be flexible enough so that it can display the messages in other languages, but right now no one knows what those

languages will be.

It looks like the program needs to be internationalized.

After Internationalization

The source code for the internationalized program follows. Notice that the text of the messages is not hardcoded.

import java.util.*;

public class Sample {

static public void main(String[] args) {

String language;
String country;

if (args.length != 2) {
language = new String(“en”);
country = new String(“US”);
} else {
language = new String(args[0]);
country = new String(args[1]);
}

Locale currentLocale;
ResourceBundle messages;

currentLocale = new Locale(language, country);

messages = ResourceBundle.getBundle(“MessagesBundle”, currentLocale);
System.out.println(messages.getString(“greetings”));
System.out.println(messages.getString(“inquiry”));
System.out.println(messages.getString(“farewell”));
}
}
To compile and run this program, need these source files:

Sample.java
MessagesBundle.properties
MessagesBundle_de_DE.properties
MessagesBundle_en_US.properties
MessagesBundle_fr_FR.properties

Running the Sample Program

The internationalized program is flexible; it allows the end user to specify a language and a country on the command line. In the following example the language code

is fr (French) and the country code is FR (France), so the program displays the messages in French:

% java Sample fr FR
Bonjour.
Comment allez-vous?
Au revoir.
In the next example the language code is en (English) and the country code is US (United States) so the program displays the messages in English:

% java Sample en US
Hello.
How are you?
Goodbye.

Internationalizing the Sample Program

If you look at the internationalized source code, you’ll notice that the hardcoded English messages have been removed. Because the messages are no longer hardcoded and

because the language code is specified at run time, the same executable can be distributed worldwide. No recompilation is required for localization. The program has

been internationalized.

1. Create the Properties Files

A properties file stores information about the characteristics of a program or environment. A properties file is in plain-text format. Create the file with just about

any text editor.

In the example the properties files store the translatable text of the messages to be displayed. Before the program was internationalized, the English version of this

text was hardcoded in the System.out.println statements. The default properties file, which is called MessagesBundle.properties, contains the following lines:

greetings = Hello
farewell = Goodbye
inquiry = How are you?
Now that the messages are in a properties file, they can be translated into various languages. No changes to the source code are required. The French translator has

created a properties file called MessagesBundle_fr_FR.properties, which contains these lines:

greetings = Bonjour.
farewell = Au revoir.
inquiry = Comment allez-vous?
Notice that the values to the right side of the equal sign have been translated but that the keys on the left side have not been changed. These keys must not change,

because they will be referenced when program fetches the translated text.

The name of the properties file is important. For example, the name of the MessagesBundle_fr_FR.properties file contains the fr language code and the FR country code.

These codes are also used when creating a Locale object.

2. Define the Locale

The Locale object identifies a particular language and country. The following statement defines a Locale for which the language is English and the country is the

United States:

aLocale = new Locale(“en”,”US”);
The next example creates Locale objects for the French language in Canada and in France:

caLocale = new Locale(“fr”,”CA”);
frLocale = new Locale(“fr”,”FR”);
The program is flexible. Instead of using hardcoded language and country codes, the program gets them from the command line at run time:

String language = new String(args[0]);
String country = new String(args[1]);
currentLocale = new Locale(language, country);
Locale objects are only identifiers. After defining a Locale, you pass it to other objects that perform useful tasks, such as formatting dates and numbers. These

objects are locale-sensitive because their behavior varies according to Locale. A ResourceBundle is an example of a locale-sensitive object.

3. Create a ResourceBundle

ResourceBundle objects contain locale-specific objects. You use ResourceBundle objects to isolate locale-sensitive data, such as translatable text. In the sample

program the ResourceBundle is backed by the properties files that contain the message text we want to display.

The ResourceBundle is created as follows:

messages = ResourceBundle.getBundle(“MessagesBundle”, currentLocale);
The arguments passed to the getBundle method identify which properties file will be accessed. The first argument, MessagesBundle, refers to this family of properties

files:

MessagesBundle_en_US.properties
MessagesBundle_fr_FR.properties
MessagesBundle_de_DE.properties
The Locale, which is the second argument of getBundle, specifies which of the MessagesBundle files is chosen. When the Locale was created, the language code and the

country code were passed to its constructor. Note that the language and country codes follow MessagesBundle in the names of the properties files.

Now all have to do is get the translated messages from the ResourceBundle.

4. Fetch the Text from the ResourceBundle

The properties files contain key-value pairs. The values consist of the translated text that the program will display. Specify the keys when fetching the translated

messages from the ResourceBundle with the getString method. For example, to retrieve the message identified by the greetings key, you invoke getString as follows:

String msg1 = messages.getString(“greetings”);
The sample program uses the key greetings because it reflects the content of the message, but it could have used another String, such as s1 or msg1. Just remember that

the key is hardcoded in the program and it must be present in the properties files. If translators accidentally modify the keys in the properties files, getString

won’t be able to find the messages.

Servlet Lifecycle

Hi friends,  in this post we will take an overview of servlet lifecycle.

First of all lets just know what is  servlet?

Servlet is a java program which runs on server side. Servlet interacts with the client via request-response. It is nothing but HTML code embedded into java code.

When any servlet get called container first checks that whether the object of requested servlet is already exists, if not then container instantiates the object and then servlet lifecycle starts with call to init method.

init() – This method gets called only once in lifecycle of the servlet. We can override this method to write the code which we want to execute only once. Object of ServletConfig is passed to this method, which contains the configuration/initialization values stated in web.xml

service() – This method gets called by the container whenever any request comes from the client for that servlet. In this method ServletRequest and ServletResponse objects are passed as arguments to this method. ServletRequest object contains the request from the client.

destroy() – It is called by the server when any servlet is no longer necessary or want to keep the servlet out of service. Container calls this method before removing the object of the servlet.

Thats how servlet lifecycle works.

Happy Coding……..!

Java : Object oriented programming language (Part – 1)

Java is a programming language developed by James Gosling at Sun Microsystems. It is an object oriented programming language. Now, what is mean by ‘Object oriented’ ? In object oriented programming, everything is in the form of object. Objects are the fundamental units in object oriented language, which are having their own behavior, specific purpose.

Syntax of Java is just like C++. One of the key feature of Java is, it is platform independent language, which makes Java language as most powerful language among the other languages. Platform independent means program written on one platform can run on any other platform provided the platform must have JVM (Java Virtual Machine).

As Java is an object oriented language it follows all the four features of it. They are as follows :

1. Inheritance

2. Encapsulation

3. Polymorphism

4. Data Binding.

Happy Coding……………..!!!!!!!!!!!