Sunday 3 December 2017

Free hosting by using OpenShift as well as create free Private Repositories using bitbucket.

Source: OpenShift Tutorials

Using a Repository SSH Key

The first step to using a private Git repository on Bitbucket using a repository SSH key is to generate the SSH key pair to be used with that repository. Remember that it is recommended to use a distinct SSH key pair. Do not use your primary identity SSH key as you will need to upload the private key file of the SSH key pair to OpenShift.
$ ssh-keygen -C "openshift-source-builder
/repo@bitbucket" -f repo-at-bitbucket -N''
To register the repository SSH key with your private repository on Bitbucket, go to the Settings for the repository.
On Bitbucket the repository SSH key is referred to by the term Access key. Search down the settings page and find the Access keys section and select it.

Click on the Add key button. In the popup window, give the key a name and paste in the contents of the public key file from the SSH key pair. This is the file with the .pub extension, which in our case is called repo-at-bitbucket.pub.
Bitbucket repository SSH keys provide read-only access and it is not possible to enable them as having write access.

Upon clicking on Add key the key will be registered for the repository.

The next step is to create a secret in OpenShift to hold the private key of the SSH key pair. We showed how to do this using both the web console and command line in prior posts. When using the command line, this was done by creating the secret:
$ oc secrets new-sshauth repo-at-bitbucket --ssh-privatekey=repo-at-bitbucket
and enabling access to the secret from the builder service account:
$ oc secrets link builder repo-at-bitbucket
In order that OpenShift knows the secret is for our private Git repository, we annotate the secret with the complete SSH form of the URI for the repository, including ssh://, dropping any user credentials in the URI in the process.
$ oc annotate secret/repo-at-bitbucket \
    'build.openshift.io/source-secret
-match-uri-1=ssh://
bitbucket.org/grahamdumpleton/
private-repo.git'
We can then deploy our application from the private Git repository.
$ oc new-app httpd~git@bitbucket.org
:grahamdumpleton/private-repo.git --name
 mysite

Using a Personal Access Token

If the OpenShift cluster you are using is located behind a corporate firewall and SSH connections are blocked, you need to use a personal access token and HTTPS connection instead.
From the web interface of Bitbucket browse to your Bitbucket settings.
On Bitbucket a personal access token is referred to by the term App password. Search down the settings page and find the App passwords section, click on it and then Create app password.

Enter in a name for the token and enable the Read checkbox against Repositories. This ensures that a user of the personal access token has read-only access to any repositories.
They will still be able to read any repositories the account has write access to. This is one of the reasons why read-only repository SSH keys bound to a specific repository are preferred.
When you are done with setting the permissions for the personal access token, click on Create and you will be shown the value of the token. Make sure you make a copy of this as you cannot view it later on in the Bitbucket settings.

We now need to create the secret from the command line using the oc secrets new-basicauth command, remembering to run oc secrets link to allow the builder service account to use it.
$ oc secret new-basicauth user-at-bitbucket --username=machineuser --prompt

$ oc secrets link builder user-at-bitbucket
You will need to supply the name of the user account which the personal access token was created under. It is better to create a machine user account for an organization, which has access to the repository, rather than use a personal user account.
The --prompt option means you will be asked to enter in the access token as the password. You could instead use the --password option and supply it on the command line.
Next, annotate the secret with the URI for the repository. Because we are using a personal access token, this will be the HTTPS URI for the repository.
$ oc annotate secret/user-at-bitbucket \
    'build.openshift.io/source-secret-match-uri-1=https://bitbucket.org/
osevg/private-repo.git'
We can then deploy our application from the private Git repository.
$ oc new-app httpd~https://bitbucket.org/osevg/
private-repo.git --name mysite

Using Private Git Repositories

This is the end of the blog series on using private Git repositories with OpenShift. In these posts we have covered the different protocols and credential types you can use to access a hosted Git repository, as well as listed some best practices around the credential type used. We looked at setting up and using repository SSH keys and personal access tokens with the major Git repository hosting services. The main posts used GitHub as the hosting service, but we also summarised key details when using GitLab and Bitbucket in subsequent posts.
Links to all the posts are:
Categories
OpenShift Container Platform, OpenShift Dedicated, OpenShift Ecosystem, OpenShift Online, OpenShift Origin
Tags
, ,

How to a create free private repository using BITBUCKET. Now no need to Share your code unwillingly.Use BitBucket Cloud.


Bitbucket commit message

Create a Git repository

As our new Bitbucket space station administrator, you need to be organized. When you make files for your space station, you’ll want to keep them in one place and shareable with teammates, no matter where they are in the universe. With Bitbucket, that means adding everything to a repository. Let’s create one!
  • Some fun facts about repositories
    • You have access to all files in your local repository, whether you are working on one file or multiple files.
    • You can view public repositories without a Bitbucket account if you have the URL for that repository.
    • Each repository belongs to a user account or a team. In the case of a user account, that user owns the repository. + In the case of a team, that team owns it.
    • The repository owner is the only person who can delete the repository. If the repository belongs to a team, an admin can delete the repository.
    • A code project can consist of multiple repositories across multiple accounts but can also be a single repository from a single account.
    • Each repository has a 2 GB size limit, but we recommend keeping your repository no larger than 1 GB.

Step 1. Create the repository

Initially, the repository you create in Bitbucket is going to be empty without any code in it. That's okay because you will start adding some files to it soon. This Bitbucket repository will be the central repository for your files, which means that others can access that repository if you give them permission. After creating a repository, you'll copy a version to your local system—that way you can update it from one repo, then transfer those changes to the other.
Central Repo to Local Repo
Do the following to create your repository:
  1. From Bitbucket, click the + icon in the global sidebar and select Repository.
    Create Repo Menu
    Bitbucket displays the Create a new repository page. Take some time to review the dialog's contents. With the exception of the Repository type, everything you enter on this page you can later change.
    Create the repository
  2. Enter BitbucketStationLocations for the Name field. Bitbucket uses this Name in the URL of the repository. For example, if the user the_best has a repository called awesome_repo, the URL for that repository would be https://bitbucket.org/the_best/awesome_repo.
  3. For Access level, leave the This is a private repository box checked. A private repository is only visible to you and those you give access to. If this box is unchecked, everyone can see your repository.
  4. Pick Git for the Repository type. Keep in mind that you can't change the repository type after you click Create repository.
  5. Click Create repository. Bitbucket creates your repository and displays its Overview page.

Step 2. Explore your new repository

Take some time to explore the repository you have just created. You should be on the repository's Overview page:
Repository Overview Click + from the global sidebar for common actions for a repository. Click items in the navigation sidebar to see what's behind each one, including Settings to update repository details and other settings. To view the shortcuts available to navigate these items, press the ? key on your keyboard.
When you click the Commits option in the sidebar, you find that you have no commits because you have not created any content for your repository. Your repository is private and you have not invited anyone to the repository, so the only person who can create or edit the repository's content right now is you, the repository owner.

Copy your Git repository and add files

Now that you have a place to add and share your space station files, you need a way to get to it from your local system. To set that up, you want to copy the Bitbucket repository to your system. Git refers to copying a repository as "cloning" it. When you clone a repository, you create a connection between the Bitbucket server (which Git knows as origin) and your local system.
 You are about to use a whole bunch of Git and non-Git commands from a terminal. If you've never used the command line before, learn where to find it at The Command Line Crash Course.

Step 1. Clone your repository to your local system

Open a browser and a terminal window from your desktop. After opening the terminal window, do the following:
  1. Navigate to your home (~) directory.
    $ cd ~
    As you use Bitbucket more, you will probably work in multiple repositories. For that reason, it's a good idea to create a directory to contain all those repositories.
  2. Create a directory to contain your repositories.
    $ mkdir repos
  3. From the terminal, update the directory you want to work in to your new repos directory.
    $ cd ~/repos
  4. From Bitbucket, go to your BitbucketStationLocations repository.
  5. Click the + icon in the global sidebar and select Clone this repository.
    Bitbucket displays a pop-up clone dialog. By default, the clone dialog sets the protocol to HTTPS or SSH, depending on your settings. For the purposes of this tutorial, don't change your default protocol.

    Clone dialog

  6. Copy the highlighted clone command.
  7. From your terminal window, paste the command you copied from Bitbucket and press Return.
  8. Enter your Bitbucket password when the terminal asks for it. If you created an account by linking to Google, use your password for that account.
    • If you experience a Windows password error:
      • In some versions of Microsoft Windows operating system and Git you might see an error similar to the one in the following example.

        Windows clone password error example

         $ git clone
        https://emmap1@bitbucket.org/emmap1/bitbucketstationlocations.
        git
        Cloning into 'bitbucketspacestation'...
        fatal: could not read
        Password for 'https://emmap1@bitbucket.org': 
        No such file or directory
      • If you get this error, enter the following at the command line:
         $ git config --global core.askpass
      • Then go back to step 4 and repeat the clone process. The bash agent should now prompt you for your password. You should only have to do this once.
      At this point, your terminal window should look similar to this:
       
      $ cd ~/repos
      $ git clone https://emmap1@bitbucket.org/emmap1/
      bitbucketstationlocations.git
      Cloning into 'bitbucketstationlocations'...
      Password
      warning: You appear to have cloned an empty repository.
      You already knew that your repository was empty right? Remember that you have added no source files to it yet.
  9. List the contents of your repos directory and you should see your bitbucketstationlocations directory in it.
    $ ls
Congratulations! You've cloned your repository to your local system.

Step 2. Add a file to your local repository and put it on Bitbucket

With the repository on your local system, it's time to get to work. You want to start keeping track of all your space station locations. To do so, let's create a file about all your locations.
  1. Go to your terminal window and navigate to the top level of your local repository.
    $ cd ~/repos/bitbucketstationlocations/
  2. Enter the following line into your terminal window to create a new file with content.
    $ echo "Earth's Moon" >> locations.txt
    If the command line doesn't return anything, it means you created the file correctly!
  3. Get the status of your local repository. The git status command tells you about how your project is progressing in comparison to your Bitbucket repository.
    At this point, Git is aware that you created a new file, and you'll see something like this:
    $ git status
    On branch master
    Initial commit
    Untracked files:
    (use "git add <file>..." to include in what will be committed)
    locations.txt
    nothing added to commit but untracked files present 
    (use "git add" to track)
    The file is untracked, meaning that Git sees a file not part of a previous commit. The status output also shows you the next step: adding the file.
  4. Tell Git to track your new locations.txt file using the git add command. Just like when you created a file, the git add command doesn't return anything when you enter it correctly.
    $ git add locations.txt
    The git add command moves changes from the working directory to the Git staging area. The staging area is where you prepare a snapshot of a set of changes before committing them to the official history.

    Git add staging

  5. Check the status of the file.
    $ git status
    On branch master
    Initial commit
    Changes to be committed:
    (use "git rm --cached <file>..." to unstage)
    new file: locations.txt
    Now you can see the new file has been added (staged) and you can commit it when you are ready. The git status command displays the state of the working directory and the staged snapshot.
  6. Issue the git commit command with a commit message, as shown on the next line. The -m indicates that a commit message follows.
    $ git commit -m 'Initial commit'
    [master (root-commit) fedc3d3] Initial commit
    1 file changed, 1 insertion(+)
    create mode 100644 locations.txt
    The git commit takes the staged snapshot and commits it to the project history. Combined with git add, this process defines the basic workflow for all Git users.

    Git commit

    Up until this point, everything you have done is on your local system and invisible to your Bitbucket repository until you push those changes.
    • Learn a bit more about Git and remote repositories
      • Git's ability to communicate with remote repositories (in your case, Bitbucket is the remote repository) is the foundation of every Git-based collaboration workflow.
      • Git's collaboration model gives every developer their own copy of the repository, complete with its own local history and branch structure. Users typically need to share a series of commits rather than a single changeset. Instead of committing a changeset from a working copy to the central repository, Git lets you share entire branches between repositories.

        Git branching

      • You manage connections with other repositories and publish local history by "pushing" branches to other repositories. You see what others have contributed by "pulling" branches into your local repository.
  7. Go back to your local terminal window and send your committed changes to Bitbucket using git push origin master. This command specifies that you are pushing to the master branch (the branch on Bitbucket) on origin (the Bitbucket server).
    You should see something similar to the following response:
    $ git push origin master
    Counting objects: 3, done.
    Writing objects: 100% (3/3), 253 bytes | 0 bytes/s, done.
    Total 3 (delta 0), reused 0 (delta 0) To https://
    emmap1@bitbucket.org/emmap1/bitbucketstationlocations.git
    * [new branch] master -> master
    Branch master set up to track remote branch master from origin.
    Your commits are now on the remote repository (origin).

    Git push

  8. Go to your BitbucketStationLocations repository on Bitbucket.
  9. If you click Commits in the sidebar, you'll see a single commit on your repository. Bitbucket combines all the things you just did into that commit and shows it to you. You can see that the Author column shows the value you used when you configured the Git global file ( ~/.gitconfig).
    If you click Source in the sidebar, you'll see that you have a single source file in your repository, the locations.txt file you just added.
    Bitbucket commits
Remember how the repository looked when you first created it? It probably looks a bit different now.

Pull changes from your Git repository on Bitbucket Cloud

Next on your list of space station administrator activities, you need a file with more details about your locations. Since you don't have many locations at the moment, you are going to add them right from Bitbucket.

Step 1. Create a file in Bitbucket

To add your new locations file, do the following:
  1. From your BitbucketStationLocations repository, click Source to open the source directory. Notice you only have one file, locations.txt , in your directory.
    Bitbucket source windowA. Branch selection: Pick the branch you want to view.
    B. Source page: Click the link to open this page.
    C. New file button: Edit and create a file in Bitbucket.
    D. Source file area: View the directory of files in Bitbucket.
  2. From the Source page, click New file in the top right corner. This button only appears after you have added at least one file to the repository.
    A page for creating the new file opens, as shown in the following image.
    Bitbucket new fileA. Branch with new file: Change if you want to add file to a different branch.
    B. New file area: Add content for your new file here.
  3. Enter stationlocations in the filename field.
  4. Select HTML from the Syntax mode list.
  5. Add the following HTML code into the text box:
    <p>Bitbucket has the following space stations:</p>
    <p>
    <b>Earth's Moon</b><br>
    Headquarters
    </p>
  6. Click Commit. The Commit message field appears with the message: stationlocations created online with Bitbucket.
  7. Click Commit under the message field.
You now have a new file in Bitbucket! You are taken to a page with details of the commit, where you can see the change you just made:
If you want to see a list of the commits you've made so far, click Commits in the sidebar.

Step 2. Pull changes from a remote repository

Now we need to get that new file into your local repository. The process is pretty straight forward, basically just the reverse of the push you used to get the locations.txt file into Bitbucket.
To pull the file into your local repository, do the following:
  1. Open your terminal window and navigate to the top level of your local repository.
    $ cd ~/repos/bitbucketstationlocations/
  2. Enter the git pull --all command to pull all the changes from Bitbucket. (In more complex branching workflows, pulling and merging all changes might not be appropriate .) Enter your Bitbucket password when asked for it. Your terminal should look similar to the following:
    $ git pull --all
    Fetching origin
    remote: Counting objects: 3, done.
    remote: Compressing objects: 100% (3/3), done.
    remote: Total 3 (delta 0), reused 0 (delta 0)
    Unpacking objects: 100% (3/3), done.
    From https://bitbucket.org/emmap1/bitbucketstationlocations
    fe5a280..fcbeeb0 master -> origin/master
    Updating fe5a280..fcbeeb0
    Fast-forward
    stationlocations | 5 ++++++++++++++
    1 file changed, 5 insertions(+)
    create mode 100644 stationlocations
    The git pull command merges the file from your remote repository (Bitbucket) into your local repository with a single command.

    Origin to Local
  3. Navigate to your repository folder on your local system and you'll see the file you just added.
Fantastic! With the addition of the two files about your space station location, you have performed the basic Git workflow (clone, add, commit, push, and pull) between Bitbucket and your local system.

Use a Git branch to merge a file

Being a space station administrator comes with certain responsibilities. Sometimes you’ll need to keep information locked down, especially when mapping out new locations in the solar system. Learning branches will allow you to update your files and only share the information when you're ready.
Branches are most powerful when you're working on a team. You can work on your own part of a project from your own branch, pull updates from Bitbucket, and then merge all your work into the main branch when it's ready. Our documentation includes more explanation of why you would want to use branches.
A branch represents an independent line of development for your repository. Think of it as a brand-new working directory, staging area, and project history. Before you create any new branches, you automatically start out with the main branch (called master ). For a visual example, this diagram shows the master branch and the other branch with a bug fix update.
Git branching

Step 1. Create a branch and make a change

Create a branch where you can add future plans for the space station that you aren't ready to commit. When you are ready to make those plans known to all, you can merge the changes into your Bitbucket repository and then delete the no-longer-needed branch.
It's important to understand that branches are just pointers to commits. When you create a branch, all Git needs to do is create a new pointer—it doesn’t create a whole new set of files or folders. Before you begin, your repository looks like this:
Master branch To create a branch, do the following:
  1. Go to your terminal window and navigate to the top level of your local repository using the following command:
    $ cd ~/repos/bitbucketstationlocations/
  2. Create a branch from your terminal window.
    $ git branch future-plans
    This command creates a branch but does not switch you to that branch, so your repository looks something like this:
    Create branch
    The repository history remains unchanged. All you get is a new pointer to the current branch. To begin working on the new branch, you have to check out the branch you want to use.
  3. Checkout the new branch you just created to start using it.
    $ git checkout future-plans
    Switched to branch 'future-plans'
    The git checkout command works hand-in-hand with git branch . Because you are creating a branch to work on something new, every time you create a new branch (with git branch), you want to make sure to check it out (with git checkout) if you're going to use it. Now that you’ve checked out the new branch, your Git workflow looks something like this:
    Feature branch
  4. Search for the bitbucketstationlocations folder on your local system and open it. You will notice there are no extra files or folders in the directory as a result of the new branch.
  5. Open the stationlocations file using a text editor.
  6. Make a change to the file by adding another station location:
    <p>Bitbucket has the following space stations:</p>
    <p>
    <b>Earth's Moon</b><br>
    Headquarters
    </p>
    <p>
    <b>Mars</b><br>
    Recreation Department
    </p>
  7. Save and close the file.
  8. Enter git status in the terminal window. You will see something like this:
    $ git status
    On branch future-plans
    Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git checkout -- <file>..." to discard changes in working directory)
    modified: stationlocations
    no changes added to commit (use "git add" and/or "git commit -a")
    Notice the On branch future-plans line? If you entered git status previously, the line was on branch master because you only had the one master branch. Before you stage or commit a change, always check this line to make sure the branch where you want to add the change is checked out.
  9. Stage your file.
    $ git add stationlocations
  10. Enter the git commit command in the terminal window, as shown with the following:
    $ git commit stationlocations -m 'making a change in a branch'
    [future-plans e3b7732] making a change in a branch
    1 file changed, 4 insertions(+)
    With this recent commit, your repository looks something like this:

    Feature branch commit

    Now it's time to merge the change that you just made back into the master branch.

Step 2. Merge your branch: fast-forward merging

Your space station is growing, and it's time for the opening ceremony of your Mars location. Now that your future plans are becoming a reality, you can merge your future-plans branch into the main branch on your local system.
Because you created only one branch and made one change, use the fast-forward branch method to merge. You can do a fast-forward merge because you have a linear path from the current branch tip to the target branch. Instead of “actually” merging the branches, all Git has to do to integrate the histories is move (i.e., “fast-forward”) the current branch tip up to the target branch tip. This effectively combines the histories, since all of the commits reachable from the target branch are now available through the current one.
Fast forward merge This branch workflow is common for short-lived topic branches with smaller changes and are not as common for longer-running features.
To complete a fast-forward merge do the following:
  1. Go to your terminal window and navigate to the top level of your local repository.
    $ cd ~/repos/bitbucketstationlocations/
  2. Enter the git status command to be sure you have all your changes committed and find out what branch you have checked out.
    $ git status
    On branch future-plans
    nothing to commit, working directory clean
  3. Switch to the master branch.
    $ git checkout master
    Switched to branch 'master'
    Your branch is up-to-date with 'origin/master'.
  4. Merge changes from the future-plans branch into the master branch. It will look something like this:
    $ git merge future-plans
    Updating fcbeeb0..e3b7732
    Fast-forward
    stationlocations | 4 ++++
    1 file changed, 4 insertions(+)
    You've essentially moved the pointer for the master branch forward to the current head and your repository looks something like the fast forward merge above.
  5. Because you don't plan on using future-plans anymore, you can delete the branch.
    $ git branch -d future-plans
    Deleted branch future-plans (was e3b7732).
    When you delete future-plans, you can still access the branch from master using a commit id. For example, if you want to undo the changes added from future-plans, use the commit id you just received to go back to that branch.
  6. Enter git status to see the results of your merge, which show that your local repository is one ahead of your remote repository. It will look something like this:
    $ git status
    On branch master
    Your branch is ahead of 'origin/master' by 1 commit.
    (use "git push" to publish your local commits)
    nothing to commit, working directory clean
Here's what you've done so far:
  • Created a branch and checked it out
  • Made a change in the new branch
  • Committed the change to the new branch
  • Integrated that change back into the main branch
  • Deleted the branch you are no longer using.
Next, we need to push all this work back up to Bitbucket, your remote repository.

Step 3. Push your change to Bitbucket

You want to make it possible for everyone else to see the location of the new space station. To do so, you can push the current state of your local repository to Bitbucket.
This diagram shows what happens when your local repository has changes that the central repository does not have and you push those changes to Bitbucket.
Before and after pushing branch Here's how to push your change to the remote repository:
  1. From the repository directory in your terminal window, enter git push origin master to push the changes. It will result in something like this:
    $ git push origin master
    Counting objects: 3, done.
    Delta compression using up to 8 threads.
    Compressing objects: 100% (3/3), done.
    Writing objects: 100% (3/3), 401 bytes | 0 bytes/s, done.
    Total 3 (delta 0), reused 0 (delta 0)
    To https://emmap1@bitbucket.org/emmap1/bitbucketstationlocations.git
    fcbeeb0..e3b7732 master -> master
  2. Click the Overview page of your Bitbucket repository, and notice you can see your push in the Recent Activity stream.
  3. Click Commits and you can see the commit you made on your local system. Notice that the change keeps the same commit id as it had on your local system.
    Commit activity
    You can also see that the line to the left of the commits list has a straight-forward path and shows no branches. That’s because the future-plans branch never interacted with the remote repository, only the change we created and committed.
  4. Click Branches and notice that the page has no record of the branch either.
  5. Click Source, and then click the stationlocations file. You can see the last change to the file has the commit id you just pushed.
  6. Click the file history list to see the changes committed for this file, which will look similar to the following figure.
    File history

You are done!

Not sure you will be able to remember all the Git commands you just learned? No problem. Bookmark our basic Git commands page so that you can refer to it when needed.

Saturday 2 December 2017

Sort Tree map in descending order.

descendingMap() method is used to return a reverse order view of the mappings contained in this map.
import java.util.*;
public class TreeMapDemo
{ public static void main(String[] args)
{
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
  treemap.put(2, "two");
treemap.put(1, "one");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(5, "five");
Navigable map nmap=treemap.descendingMap();
  System.out.println(nmap); } }



If you can not clear the programming interviews, solution is here.

You don't need to work in any company. Make a blog. If you haven't learn any thing seriously in btech. Learn it madly. And put what you learn as well as your experiences on blog.


Earn some money by blog using adsense.


You have a clear open option to create any startups,As you are not getting job.


Spend some time with family. Or travel the whole India by giving interviews. I'm pretty serious as I travelled almost all the regions of India for attending interviews.


I saw TajMahal, Red Fort, India Gate, Gate Way Of India etc. first time after btech. And I got these chances because of these interviews. So never get negative and always use you time in some creative things.


I have also started a blog and making money by adsense. You can see it atSHIVAM SHUKLA'S BLOG


Always try to do some creative work in your field and you will never get upset as well as keep a full focus on job searching and put your best effort in interviews.


All the best


Friday 1 December 2017

Simple and clear Difference between Hashmap, Linkedhashmap, TreeMap

Hash map doesn't preserves the insertion order .
Example. Hashmap If you are inserting keys as


1 3
5 9
4 6
7 15
3 10

It can store it as


4 6
5 9
3 10
1 3
7 15

Linked Hashmap preserves the insertion order.


Example.
If you are inserting keys


1 3
5 9
4 6
7 15
3 10

It will store it as


1 3
5 9
4 6
7 15
3 10

same as we insert.


Tree map stores the vales in Increasing Order Of Keys. Example.
If you are inserting keys


1 3
5 9
4 6
7 15
3 10

It will store it as


1 3
3 10
4 6
5 9
7 15

Wednesday 29 November 2017

Getting all the substrings of all the Permutations of a string in java.

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
public class CharString {
public static void main(String []args)throws IOException{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    ArrayList<String>al=new ArrayList<String>();
    HashSet<String>ht=new HashSet<String>();
    String s=br.readLine().trim();
    perm(al,"",s);
    for(String ss:al){
        for(int i=0;i<ss.length();i++){
            for(int j=i+1;j<=ss.length();j++){
                //System.out.println(ss.substring(i,j));
                ht.add(ss.substring(i,j));
               
            }
           
        }
        String g="abcdef";
        System.out.println(g.substring(5,6));
       
       
    }
    for(String ss:ht)
        System.out.println(ss);
   
   
   
}
public static ArrayList<String>perm(ArrayList<String>al,String prefix,String s){
    int n=s.length();
    if(n==0)
        al.add(prefix);
    else{
        for(int i=0;i<n;i++)
        perm(al,prefix+s.charAt(i),s.substring(0, i)+s.substring(i+1, n));
       
       
    }
   
   
   
    return al;
   
   
   
}
}


Misunderstandings with java string..

Because String is immutable so changes will not occur if you will not assign the returned value of function to the string.so in your question assign value of swap function  returned value to s.


s=swap(s, n1, n2) ;then the value of string s will change.


I was also getting the unchanged value when i was writing the program to get some permutations string(Although it is not giving all the permutations but this is for example to answer your question)


Here is a example.


import java.io.*;
public class MyString { public static void main(String []args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine().trim(); int n=0;int k=0;
while(n!=s.length())
{ while(k<n){
swap(s,k,n); System.out.println(s); swap(s,k,n); k++; } n++; } }
public static void swap(String s,int n1,int n2)
{ char temp; temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s); sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString(); } }

but i was not getting the permuted values of the string from above code.So I assigned the returned value of the swap function to the string and got changed values of string. after assigning the returned value i got the permuted values of string.


//import java.util.*; import java.io.*; public class MyString { public static void main(String []args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine().trim(); int n=0;int k=0;
while(n!=s.length()){ while(k<n){ s=swap(s,k,n);
System.out.println(s); s=swap(s,k,n); k++; } n++; } }
public static String swap(String s,int n1,int n2){
char temp; temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s); sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString(); return s; } }

How to create a git repository.

A new repo from scratch


Say you’ve just got some data from a collaborator and are about to start exploring it.


Create a directory to contain the project.


Go into the new directory.


Type git init.


Write some code.


Type git add to add the files (see the typical use page).


Type git commit.


The first file to create (and add and commit) is probably a ReadMe file, either as plain text or withMarkdown, describing the project.


Markdown allows you to add a bit of text markup, like hyperlinksbold/italics, or to indicate code with a monospace font. Markdown is easily converted to html for viewing in a web browser, and GitHub will do this for you automatically.


A new repo from an existing project


Say you’ve got an existing project that you want to start tracking with git.


Go into the directory containing the project.


Type git init.


Type git add to add all of the relevant files.


You’ll probably want to create a .gitignore file right away, to indicate all of the files you don’t want to track. Use git add .gitignore, too.


Type git commit.


Connect it to github


You’ve now got a local git repository. You can use git locally, like that, if you want. But if you want the thing to have a home on github, do the following.


Go to github.


Log in to your account.


Click the new repository button in the top-right. You’ll have an option there to initialize the repository with a README file, but I don’t.


Click the “Create repository” button.


Now, follow the second set of instructions, “Push an existing repository…”


$ git remote add origin git@github.com:username/new_repo $ git push -u origin master


Actually, the first line of the instructions will say


$ git remote add origin https://github.com/username/new_repo


But I use git@github.com:username/new_reporather than https://github.com/username/new_repo, as the former is for use with ssh (if you set up ssh as I mentioned in “Your first time”, then you won’t have to type your password every time you push things to github). If you use the latter construction, you’ll have to type your github password every time you push to github.

Tuesday 28 November 2017

Why Using Maven Is So Simple. Guide To Maven....

Maven Getting Started Guide

This guide is intended as a reference for those working with Maven for the first time, but is also intended to serve as a cookbook with self-contained references and solutions for common use cases. For first time users, it is recommended that you step through the material in a sequential fashion. For users more familiar with Maven, this guide endeavours to provide a quick solution for the need at hand. It is assumed at this point that you have downloaded Maven and installed Maven on your local machine. If you have not done so please refer to the Download and Installation instructions.
Ok, so you now have Maven installed and we're ready to go. Before we jump into our examples we'll very briefly go over what Maven is and how it can help you with your daily work and collaborative efforts with team members. Maven will, of course, work for small projects, but Maven shines in helping teams operate more effectively by allowing team members to focus on what the stakeholders of a project require. You can leave the build infrastructure to Maven!

Sections

What is Maven?

At first glance Maven can appear to be many things, but in a nutshell Maven is an attempt to apply patterns to a project's build infrastructure in order to promote comprehension and productivity by providing a clear path in the use of best practices. Maven is essentially a project management and comprehension tool and as such provides a way to help with managing:
  • Builds
  • Documentation
  • Reporting
  • Dependencies
  • SCMs
  • Releases
  • Distribution
If you want more background information on Maven you can check out The Philosophy of Maven and The History of Maven. Now let's move on to how you, the user, can benefit from using Maven.

How can Maven benefit my development process?

Maven can provide benefits for your build process by employing standard conventions and practices to accelerate your development cycle while at the same time helping you achieve a higher rate of success.
Now that we have covered a little bit of the history and purpose of Maven let's get into some real examples to get you up and running with Maven!

How do I setup Maven?

The defaults for Maven are often sufficient, but if you need to change the cache location or are behind a HTTP proxy, you will need to create configuration. See the Guide to Configuring Maven for more information.

How do I make my first Maven project?

We are going to jump headlong into creating your first Maven project! To create our first Maven project we are going to use Maven's archetype mechanism. An archetype is defined as an original pattern or model from which all other things of the same kind are made. In Maven, an archetype is a template of a project which is combined with some user input to produce a working Maven project that has been tailored to the user's requirements. We are going to show you how the archetype mechanism works now, but if you would like to know more about archetypes please refer to our Introduction to Archetypes.
On to creating your first project! In order to create the simplest of Maven projects, execute the following from the command line:
  1. mvn -B archetype:generate \
  2. -DarchetypeGroupId=org.apache.maven.archetypes \
  3. -DgroupId=com.mycompany.app \
  4. -DartifactId=my-app
Once you have executed this command, you will notice a few things have happened. First, you will notice that a directory named my-app has been created for the new project, and this directory contains a file named pom.xml that should look like this:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.mycompany.app</groupId>
  7. <artifactId>my-app</artifactId>
  8. <packaging>jar</packaging>
  9. <version>1.0-SNAPSHOT</version>
  10. <name>Maven Quick Start Archetype</name>
  11. <url>http://maven.apache.org</url>
  12. <dependencies>
  13. <dependency>
  14. <groupId>junit</groupId>
  15. <artifactId>junit</artifactId>
  16. <version>4.11</version>
  17. <scope>test</scope>
  18. </dependency>
  19. </dependencies>
  20. </project>
pom.xml contains the Project Object Model (POM) for this project. The POM is the basic unit of work in Maven. This is important to remember because Maven is inherently project-centric in that everything revolves around the notion of a project. In short, the POM contains every important piece of information about your project and is essentially one-stop-shopping for finding anything related to your project. Understanding the POM is important and new users are encouraged to refer to the Introduction to the POM.
This is a very simple POM but still displays the key elements every POM contains, so let's walk through each of them to familiarize you with the POM essentials:
  • project This is the top-level element in all Maven pom.xml files.
  • modelVersion This element indicates what version of the object model this POM is using. The version of the model itself changes very infrequently but it is mandatory in order to ensure stability of use if and when the Maven developers deem it necessary to change the model.
  • groupId This element indicates the unique identifier of the organization or group that created the project. The groupId is one of the key identifiers of a project and is typically based on the fully qualified domain name of your organization. For example org.apache.maven.plugins is the designated groupId for all Maven plugins.
  • artifactId This element indicates the unique base name of the primary artifact being generated by this project. The primary artifact for a project is typically a JAR file. Secondary artifacts like source bundles also use the artifactId as part of their final name. A typical artifact produced by Maven would have the form <artifactId>-<version>.<extension> (for example, myapp-1.0.jar).
  • packaging This element indicates the package type to be used by this artifact (e.g. JAR, WAR, EAR, etc.). This not only means if the artifact produced is JAR, WAR, or EAR but can also indicate a specific lifecycle to use as part of the build process. (The lifecycle is a topic we will deal with further on in the guide. For now, just keep in mind that the indicated packaging of a project can play a part in customizing the build lifecycle.) The default value for the packaging element is JAR so you do not have to specify this for most projects.
  • version This element indicates the version of the artifact generated by the project. Maven goes a long way to help you with version management and you will often see the SNAPSHOT designator in a version, which indicates that a project is in a state of development. We will discuss the use of snapshots and how they work further on in this guide.
  • name This element indicates the display name used for the project. This is often used in Maven's generated documentation.
  • url This element indicates where the project's site can be found. This is often used in Maven's generated documentation.
  • description This element provides a basic description of your project. This is often used in Maven's generated documentation.
For a complete reference of what elements are available for use in the POM please refer to our POM Reference. Now let's get back to the project at hand.
After the archetype generation of your first project you will also notice that the following directory structure has been created:
  1. my-app
  2. |-- pom.xml
  3. `-- src
  4. |-- main
  5. | `-- java
  6. | `-- com
  7. | `-- mycompany
  8. | `-- app
  9. | `-- App.java
  10. `-- test
  11. `-- java
  12. `-- com
  13. `-- mycompany
  14. `-- app
  15. `-- AppTest.java
As you can see, the project created from the archetype has a POM, a source tree for your application's sources and a source tree for your test sources. This is the standard layout for Maven projects (the application sources reside in ${basedir}/src/main/java and test sources reside in ${basedir}/src/test/java, where ${basedir} represents the directory containing pom.xml).
If you were to create a Maven project by hand this is the directory structure that we recommend using. This is a Maven convention and to learn more about it you can read our Introduction to the Standard Directory Layout.
Now that we have a POM, some application sources, and some test sources you are probably asking...

How do I compile my application sources?

Change to the directory where pom.xml is created by archetype:generate and execute the following command to compile your application sources:
  1. mvn compile
Upon executing this command you should see output like the following:
  1. [INFO] -------------------------------------------------------
  2. [INFO] Building Maven Quick Start Archetype
  3. [INFO] task-segment: [compile]
  4. [INFO] -------------------------------------------------------
  5. [INFO] artifact
  6.  org.apache.maven.plugins:maven-resources-plugin: \
  7. checking for updates from central
  8. ...
  9. [INFO] artifact
  10.  org.apache.maven.plugins:maven-compiler-plugin: \
  11. checking for updates from central
  12. ...
  13. [INFO] [resources:resources]
  14. ...
  15. [INFO] [compiler:compile]
  16. Compiling 1 source file to <dir>/my-app/target/classes
  17. [INFO] ------------------------------------------------
  18. [INFO] BUILD SUCCESSFUL
  19. [INFO] --------------------------------------------------------
  20. [INFO] Total time: 3 minutes 54 seconds
  21. [INFO] Finished at: Fri Sep 23 15:48:34 GMT-05:00 2005
  22. [INFO] Final Memory: 2M/6M
  23. [INFO] --------------------------------------------------------
The first time you execute this (or any other) command, Maven will need to download all the plugins and related dependencies it needs to fulfill the command. From a clean installation of Maven, this can take quite a while (in the output above, it took almost 4 minutes). If you execute the command again, Maven will now have what it needs, so it won't need to download anything new and will be able to execute the command much more quickly.
As you can see from the output, the compiled classes were placed in ${basedir}/target/classes, which is another standard convention employed by Maven. So, if you're a keen observer, you'll notice that by using the standard conventions, the POM above is very small and you haven't had to tell Maven explicitly where any of your sources are or where the output should go. By following the standard Maven conventions, you can get a lot done with very little effort! Just as a casual comparison, let's take a look at what you might have had to do in Ant to accomplish the same thing.
Now, this is simply to compile a single tree of application sources and the Ant script shown is pretty much the same size as the POM shown above. But we'll see how much more we can do with just that simple POM!

How do I compile my test sources and run my unit tests?

Now you're successfully compiling your application's sources and now you've got some unit tests that you want to compile and execute (because every programmer always writes and executes their unit tests *nudge nudge wink wink*).
Execute the following command:
  1. mvn test
Upon executing this command you should see output like the following:
  1. [INFO] ---------------------------------------------------------
  2. [INFO] Building Maven Quick Start Archetype
  3. [INFO] task-segment: [test]
  4. [INFO] -----------------------------------------------------
  5. [INFO] artifact 
  6. org.apache.maven.plugins:maven-surefire-plugin: \
  7. checking for updates from central
  8. ...
  9. [INFO] [resources:resources]
  10. [INFO] [compiler:compile]
  11. [INFO] Nothing to compile - all classes are up to date
  12. [INFO] [resources:testResources]
  13. [INFO] [compiler:testCompile]
  14. Compiling 1 source file to C:\Test\Maven2\test\my-app\target\test-classes
  15. ...
  16. [INFO] [surefire:test]
  17. [INFO] Setting reports dir: C:\Test\Maven2\test\my-app\target/surefire-reports
  18.  
  19. -------------------------------------------------------
  20. T E S T S
  21. -------------------------------------------------------
  22. [surefire] Running com.mycompany.app.AppTest
  23. [surefire] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0 sec
  24.  
  25. Results :
  26. [surefire] Tests run: 1, Failures: 0, Errors: 0
  27.  
  28. [INFO] ---------------------------------------------------
  29. [INFO] BUILD SUCCESSFUL
  30. [INFO] -------------------------------------------------------
  31. [INFO] Total time: 15 seconds
  32. [INFO] Finished at: Thu Oct 06 08:12:17 MDT 2005
  33. [INFO] Final Memory: 2M/8M
  34. [INFO] ---------------------------------------------
Some things to notice about the output:
  • Maven downloads more dependencies this time. These are the dependencies and plugins necessary for executing the tests (it already has the dependencies it needs for compiling and won't download them again).
  • Before compiling and executing the tests Maven compiles the main code (all these classes are up to date because we haven't changed anything since we compiled last).
If you simply want to compile your test sources (but not execute the tests), you can execute the following:
  1. mvn test-compile
Now that you can compile your application sources, compile your tests, and execute the tests, you'll want to move on to the next logical step so you'll be asking ...

How do I create a JAR and install it in my local repository?

Making a JAR file is straight forward enough and can be accomplished by executing the following command:
  1. mvn package
If you take a look at the POM for your project you will notice the packaging element is set to jar. This is how Maven knows to produce a JAR file from the above command (we'll talk more about this later). You can now take a look in the ${basedir}/target directory and you will see the generated JAR file.
Now you'll want to install the artifact you've generated (the JAR file) in your local repository (${user.home}/.m2/repository is the default location). For more information on repositories you can refer to our Introduction to Repositories but let's move on to installing our artifact! To do so execute the following command:
  1. mvn install
Upon executing this command you should see the following output:
  1. [INFO] ------------------------------------------------------------
  2. [INFO] Building Maven Quick Start Archetype
  3. [INFO] task-segment: [install]
  4. [INFO] -------------------------------------------------------------
  5. [INFO] [resources:resources]
  6. [INFO] [compiler:compile]
  7. Compiling 1 source file to <dir>/my-app/target/classes
  8. [INFO] [resources:testResources]
  9. [INFO] [compiler:testCompile]
  10. Compiling 1 source file to <dir>/my-app/target/test-classes
  11. [INFO] [surefire:test]
  12. [INFO] Setting reports dir: <dir>/my-app/target/surefire-reports
  13.  
  14. -------------------------------------------------------
  15. T E S T S
  16. -------------------------------------------------------
  17. [surefire] Running com.mycompany.app.AppTest
  18. [surefire] Tests run: 1, Failures: 0, Errors: 0,Time elapsed:0.001 sec
  19.  
  20. Results :
  21. [surefire] Tests run: 1, Failures: 0, Errors: 0
  22.  
  23. [INFO] [jar:jar]
  24. [INFO] Building jar: <dir>/my-app/target/my-app-1.0-SNAPSHOT.jar
  25. [INFO] [install:install]
  26. [INFO] Installing <dir>/my-app/target/my-app-1.0-SNAPSHOT.jar to \
  27. <local-repository>/com/mycompany/app/my-app/1.0-SNAPSHOT/my-app-1.0- 
  28. SNAPSHOT.jar
  29. [INFO] -------------------------------------------------------------
  30. [INFO] BUILD SUCCESSFUL
  31. [INFO] --------------------------------------------------------------
  32. [INFO] Total time: 5 seconds
  33. [INFO] Finished at: Tue Oct 04 13:20:32 GMT-05:00 2005
  34. [INFO] Final Memory: 3M/8M
  35. [INFO] ---------------------------------------------------------------
Note that the surefire plugin (which executes the test) looks for tests contained in files with a particular naming convention. By default the tests included are:
  • **/*Test.java
  • **/Test*.java
  • **/*TestCase.java
And the default excludes are:
  • **/Abstract*Test.java
  • **/Abstract*TestCase.java
You have walked through the process for setting up, building, testing, packaging, and installing a typical Maven project. This is likely the vast majority of what projects will be doing with Maven and if you've noticed, everything you've been able to do up to this point has been driven by an 18-line file, namely the project's model or POM. If you look at a typical Ant build file that provides the same functionality that we've achieved thus far you'll notice it's already twice the size of the POM and we're just getting started! There is far more functionality available to you from Maven without requiring any additions to our POM as it currently stands. To get any more functionality out of our example Ant build file you must keep making error-prone additions.
So what else can you get for free? There are a great number of Maven plugins that work out of the box with even a simple POM like we have above. We'll mention one here specifically as it is one of the highly prized features of Maven: without any work on your part this POM has enough information to generate a web site for your project! You will most likely want to customize your Maven site but if you're pressed for time all you need to do to provide basic information about your project is execute the following command:
  1. mvn site
There are plenty of other standalone goals that can be executed as well, for example:
  1. mvn clean
This will remove the target directory with all the build data before starting so that it is fresh.

What is a SNAPSHOT version?

Notice the value of the version tag in the pom.xml file shown below has the suffix: -SNAPSHOT.
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. ...
  3. <groupId>...</groupId>
  4. <artifactId>my-app</artifactId>
  5. ...
  6. <version>1.0-SNAPSHOT</version>
  7. <name>Maven Quick Start Archetype</name>
  8. ...
The SNAPSHOT value refers to the 'latest' code along a development branch, and provides no guarantee the code is stable or unchanging. Conversely, the code in a 'release' version (any version value without the suffix SNAPSHOT) is unchanging.
In other words, a SNAPSHOT version is the 'development' version before the final 'release' version. The SNAPSHOT is "older" than its release.
During the release process, a version of x.y-SNAPSHOT changes to x.y. The release process also increments the development version to x.(y+1)-SNAPSHOT. For example, version 1.0-SNAPSHOT is released as version 1.0, and the new development version is version 1.1-SNAPSHOT.

How do I use plugins?

Whenever you want to customise the build for a Maven project, this is done by adding or reconfiguring plugins.
Note for Maven 1.0 Users: In Maven 1.0, you would have added some preGoal to maven.xml and some entries to project.properties. Here, it is a little different.
For this example, we will configure the Java compiler to allow JDK 5.0 sources. This is as simple as adding this to your POM:
  1. ...
  2. <build>
  3. <plugins>
  4. <plugin>
  5. <groupId>org.apache.maven.plugins</groupId>
  6. <artifactId>maven-compiler-plugin</artifactId>
  7. <version>3.3</version>
  8. <configuration>
  9. <source>1.5</source>
  10. <target>1.5</target>
  11. </configuration>
  12. </plugin>
  13. </plugins>
  14. </build>
  15. ...
You'll notice that all plugins in Maven look much like a dependency - and in some ways they are. This plugin will be automatically downloaded and used - including a specific version if you request it (the default is to use the latest available).
The configuration element applies the given parameters to every goal from the compiler plugin. In the above case, the compiler plugin is already used as part of the build process and this just changes the configuration. It is also possible to add new goals to the process, and configure specific goals. For information on this, see the Introduction to the Build Lifecycle.
To find out what configuration is available for a plugin, you can see the Plugins List and navigate to the plugin and goal you are using. For general information about how to configure the available parameters of a plugin, have a look at the Guide to Configuring Plugins.

How do I add resources to my JAR?

Another common use case that can be satisfied which requires no changes to the POM that we have above is packaging resources in the JAR file. For this common task, Maven again relies on the Standard Directory Layout, which means by using standard Maven conventions you can package resources within JARs simply by placing those resources in a standard directory structure.
You see below in our example we have added the directory ${basedir}/src/main/resources into which we place any resources we wish to package in our JAR. The simple rule employed by Maven is this: any directories or files placed within the ${basedir}/src/main/resources directory are packaged in your JAR with the exact same structure starting at the base of the JAR.
  1. my-app
  2. |-- pom.xml
  3. `-- src
  4. |-- main
  5. | |-- java
  6. | | `-- com
  7. | | `-- mycompany
  8. | | `-- app
  9. | | `-- App.java
  10. | `-- resources
  11. | `-- META-INF
  12. | `-- application.properties
  13. `-- test
  14. `-- java
  15. `-- com
  16. `-- mycompany
  17. `-- app
  18. `-- AppTest.java
So you can see in our example that we have a META-INF directory with an  
application.properties file within that directory. If you unpacked the JAR that Maven
 created for you and took a look at it you would see the following:
  1. |-- META-INF
  2. | |-- MANIFEST.MF
  3. | |-- application.properties
  4. | `-- maven
  5. | `-- com.mycompany.app
  6. | `-- my-app
  7. | |-- pom.properties
  8. | `-- pom.xml
  9. `-- com
  10. `-- mycompany
  11. `-- app
  12. `-- App.class
As you can see, the contents of ${basedir}/src/main/resources can be found starting at the base of the JAR and our application.properties file is there in the META-INF directory. You will also notice some other files there like META-INF/MANIFEST.MF as well as a pom.xml and pom.properties file. These come standard with generation of a JAR in Maven. You can create your own manifest if you choose, but Maven will generate one by default if you don't. (You can also modify the entries in the default manifest. We will touch on this later.) The pom.xml and pom.properties files are packaged up in the JAR so that each artifact produced by Maven is self-describing and also allows you to utilize the metadata in your own application if the need arises. One simple use might be to retrieve the version of your application. Operating on the POM file would require you to use some Maven utilities but the properties can be utilized using the standard Java API and look like the following:
  1. #Generated by Maven
  2. #Tue Oct 04 15:43:21 GMT-05:00 2005
  3. version=1.0-SNAPSHOT
  4. groupId=com.mycompany.app
  5. artifactId=my-app
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is ${basedir}/src/test/resources. At this point you would have a project directory structure that would look like the following:
  1. my-app
  2. |-- pom.xml
  3. `-- src
  4. |-- main
  5. | |-- java
  6. | | `-- com
  7. | | `-- mycompany
  8. | | `-- app
  9. | | `-- App.java
  10. | `-- resources
  11. | `-- META-INF
  12. | |-- application.properties
  13. `-- test
  14. |-- java
  15. | `-- com
  16. | `-- mycompany
  17. | `-- app
  18. | `-- AppTest.java
  19. `-- resources
  20. `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource
required for testing:
  1. ...
  2.  
  3. // Retrieve resource
  4. InputStream is = getClass().getResourceAsStream( "/test.properties" );
  5.  
  6. // Do something with the resource
  7.  
  8. ...

How do I filter resource files?

Sometimes a resource file will need to contain a value that can only be supplied at build time. To accomplish this in Maven, put a reference to the property that will contain the value into your resource file using the syntax ${<property name>}. The property can be one of the values defined in your pom.xml, a value defined in the user's settings.xml, a property defined in an external properties file, or a system property.
To have Maven filter resources when copying, simply set filtering to true for the resource directory in your pom.xml:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>my-app</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <name>Maven Quick Start Archetype</name>
  13. <url>http://maven.apache.org</url>
  14.  
  15. <dependencies>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>4.11</version>
  20. <scope>test</scope>
  21. </dependency>
  22. </dependencies>
  23.  
  24. <build>
  25. <resources>
  26. <resource>
  27. <directory>src/main/resources</directory>
  28. <filtering>true</filtering>
  29. </resource>
  30. </resources>
  31. </build>
  32. </project>
You'll notice that we had to add the build, resources, and resource elements which weren't there before. In addition, we had to explicitly state that the resources are located in the src/main/resources directory. All of this information was provided as default values previously, but because the default value for filtering is false, we had to add this to our pom.xml in order to override that default value and set filtering to true.
To reference a property defined in your pom.xml, the property name uses the names of the XML elements that define the value, with "pom" being allowed as an alias for the project (root) element. So ${project.name} refers to the name of the project, ${project.version} refers to the version of the project, ${project.build.finalName} refers to the final name of the file created when the built project is packaged, etc. Note that some elements of the POM have default values, so don't need to be explicitly defined in your pom.xml for the values to be available here. Similarly, values in the user's settings.xml can be referenced using property names beginning with "settings" (for example, ${settings.localRepository} refers to the path of the user's local repository).
To continue our example, let's add a couple of properties to the application.properties file (which we put in the src/main/resources directory) whose values will be supplied when the resource is filtered:
  1. # application.properties
  2. application.name=${project.name}
  3. application.version=${project.version}
With that in place, you can execute the following command (process-resources is the build lifecycle phase where the resources are copied and filtered):
  1. mvn process-resources
and the application.properties file under target/classes (and will eventually go into the jar) looks like this:
  1. # application.properties
  2. application.name=Maven Quick Start Archetype
  3. application.version=1.0-SNAPSHOT
To reference a property defined in an external file, all you need to do is add a reference to this external file in your pom.xml. First, let's create our external properties file and call it src/main/filters/filter.properties:
  1. # filter.properties
  2. my.filter.value=hello!
Next, we'll add a reference to this new file in the pom.xml:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>my-app</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <name>Maven Quick Start Archetype</name>
  13. <url>http://maven.apache.org</url>
  14.  
  15. <dependencies>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>4.11</version>
  20. <scope>test</scope>
  21. </dependency>
  22. </dependencies>
  23.  
  24. <build>
  25. <filters>
  26. <filter>src/main/filters/filter.properties</filter>
  27. </filters>
  28. <resources>
  29. <resource>
  30. <directory>src/main/resources</directory>
  31. <filtering>true</filtering>
  32. </resource>
  33. </resources>
  34. </build>
  35. </project>
Then, if we add a reference to this property in the application.properties file:
  1. # application.properties
  2. application.name=${project.name}
  3. application.version=${project.version}
  4. message=${my.filter.value}
the next execution of the mvn process-resources command will put our new property value into application.properties. As an alternative to defining the my.filter.value property in an external file, you could also have defined it in the properties section of your pom.xml and you'd get the same effect (notice I don't need the references to src/main/filters/filter.properties either):
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>my-app</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <name>Maven Quick Start Archetype</name>
  13. <url>http://maven.apache.org</url>
  14.  
  15. <dependencies>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>4.11</version>
  20. <scope>test</scope>
  21. </dependency>
  22. </dependencies>
  23.  
  24. <build>
  25. <resources>
  26. <resource>
  27. <directory>src/main/resources</directory>
  28. <filtering>true</filtering>
  29. </resource>
  30. </resources>
  31. </build>
  32.  
  33. <properties>
  34. <my.filter.value>hello</my.filter.value>
  35. </properties>
  36. </project>
Filtering resources can also get values from system properties; either the system properties built into Java (like java.version or user.home) or properties defined on the command line using the standard Java -D parameter. To continue the example, let's change our application.properties file to look like this:
  1. # application.properties
  2. java.version=${java.version}
  3. command.line.prop=${command.line.prop}
Now, when you execute the following command (note the definition of the command.line.prop property on the command line), the application.properties file will contain the values from the system properties.
  1. mvn process-resources "-Dcommand.line.prop=hello again"

How do I use external dependencies?

You've probably already noticed a dependencies element in the POM we've been using as an example. You have, in fact, been using an external dependency all this time, but here we'll talk about how this works in a bit more detail. For a more thorough introduction, please refer to our Introduction to Dependency Mechanism.
The dependencies section of the pom.xml lists all of the external dependencies that our project needs in order to build (whether it needs that dependency at compile time, test time, run time, or whatever). Right now, our project is depending on JUnit only (I took out all of the resource filtering stuff for clarity):
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>my-app</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <name>Maven Quick Start Archetype</name>
  13. <url>http://maven.apache.org</url>
  14.  
  15. <dependencies>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>4.11</version>
  20. <scope>test</scope>
  21. </dependency>
  22. </dependencies>
  23. </project>
For each external dependency, you'll need to define at least 4 things: groupId, artifactId, version, and scope. The groupId, artifactId, and version are the same as those given in the pom.xml for the project that built that dependency. The scope element indicates how your project uses that dependency, and can be values like compile, test, and runtime. For more information on everything you can specify for a dependency, see the Project Descriptor Reference.
For more information about the dependency mechanism as a whole, see Introduction to Dependency Mechanism.
With this information about a dependency, Maven will be able to reference the dependency when it builds the project. Where does Maven reference the dependency from? Maven looks in your local repository (${user.home}/.m2/repository is the default location) to find all dependencies. In a previous section, we installed the artifact from our project (my-app-1.0-SNAPSHOT.jar) into the local repository. Once it's installed there, another project can reference that jar as a dependency simply by adding the dependency information to its pom.xml:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <groupId>com.mycompany.app</groupId>
  6. <artifactId>my-other-app</artifactId>
  7. ...
  8. <dependencies>
  9. ...
  10. <dependency>
  11. <groupId>com.mycompany.app</groupId>
  12. <artifactId>my-app</artifactId>
  13. <version>1.0-SNAPSHOT</version>
  14. <scope>compile</scope>
  15. </dependency>
  16. </dependencies>
  17. </project>
What about dependencies built somewhere else? How do they get into my local repository? Whenever a project references a dependency that isn't available in the local repository, Maven will download the dependency from a remote repository into the local repository. You probably noticed Maven downloading a lot of things when you built your very first project (these downloads were dependencies for the various plugins used to build the project). By default, the remote repository Maven uses can be found (and browsed) at http://repo.maven.apache.org/maven2/. You can also set up your own remote repository (maybe a central repository for your company) to use instead of or in addition to the default remote repository. For more information on repositories you can refer to the Introduction to Repositories.
Let's add another dependency to our project. Let's say we've added some logging to the code and need to add log4j as a dependency. First, we need to know what the groupId, artifactId, and version are for log4j. We can browse ibiblio and look for it, or use Google to help by searching for "site:www.ibiblio.org maven2 log4j". The search shows a directory called /maven2/log4j/log4j (or /pub/packages/maven2/log4j/log4j). In that directory is a file called maven-metadata.xml. Here's what the maven-metadata.xml for log4j looks like:
  1. <metadata>
  2. <groupId>log4j</groupId>
  3. <artifactId>log4j</artifactId>
  4. <version>1.1.3</version>
  5. <versioning>
  6. <versions>
  7. <version>1.1.3</version>
  8. <version>1.2.4</version>
  9. <version>1.2.5</version>
  10. <version>1.2.6</version>
  11. <version>1.2.7</version>
  12. <version>1.2.8</version>
  13. <version>1.2.11</version>
  14. <version>1.2.9</version>
  15. <version>1.2.12</version>
  16. </versions>
  17. </versioning>
  18. </metadata>
From this file, we can see that the groupId we want is "log4j" and the artifactId is "log4j". We see lots of different version values to choose from; for now, we'll just use the latest version, 1.2.12 (some maven-metadata.xml files may also specify which version is the current release version). Alongside the maven-metadata.xml file, we can see a directory corresponding to each version of the log4j library. Inside each of these, we'll find the actual jar file (e.g. log4j-1.2.12.jar) as well as a pom file (this is the pom.xml for the dependency, indicating any further dependencies it might have and other information) and another maven-metadata.xml file. There's also an md5 file corresponding to each of these, which contains an MD5 hash for these files. You can use this to authenticate the library or to figure out which version of a particular library you may be using already.
Now that we know the information we need, we can add the dependency to our pom.xml:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>my-app</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <name>Maven Quick Start Archetype</name>
  13. <url>http://maven.apache.org</url>
  14.  
  15. <dependencies>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>4.11</version>
  20. <scope>test</scope>
  21. </dependency>
  22. <dependency>
  23. <groupId>log4j</groupId>
  24. <artifactId>log4j</artifactId>
  25. <version>1.2.12</version>
  26. <scope>compile</scope>
  27. </dependency>
  28. </dependencies>
  29. </project>
Now, when we compile the project (mvn compile), we'll see Maven download the log4j dependency for us.

How do I deploy my jar in my remote repository?

For deploying jars to an external repository, you have to configure the repository url in the pom.xml and the authentication information for connectiong to the repository in the settings.xml.
Here is an example using scp and username/password authentication:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>my-app</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11.  
  12. <name>Maven Quick Start Archetype</name>
  13. <url>http://maven.apache.org</url>
  14.  
  15. <dependencies>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>4.11</version>
  20. <scope>test</scope>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.apache.codehaus.plexus</groupId>
  24. <artifactId>plexus-utils</artifactId>
  25. <version>1.0.4</version>
  26. </dependency>
  27. </dependencies>
  28.  
  29. <build>
  30. <filters>
  31. <filter>src/main/filters/filters.properties</filter>
  32. </filters>
  33. <resources>
  34. <resource>
  35. <directory>src/main/resources</directory>
  36. <filtering>true</filtering>
  37. </resource>
  38. </resources>
  39. </build>
  40. <!--
  41. |
  42. |
  43. |
  44. -->
  45. <distributionManagement>
  46. <repository>
  47. <id>mycompany-repository</id>
  48. <name>MyCompany Repository</name>
  49. <url>scp://repository.mycompany.com/repository/maven2</url>
  50. </repository>
  51. </distributionManagement>
  52. </project>
  1. <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
  4. http://maven.apache.org/xsd/settings-1.0.0.xsd">
  5. ...
  6. <servers>
  7. <server>
  8. <id>mycompany-repository</id>
  9. <username>jvanzyl</username>
  10. <!-- Default value is ~/.ssh/id_dsa -->
  11. <privateKey>/path/to/identity</privateKey>(default is ~/.ssh/id_dsa)
  12. <passphrase>my_key_passphrase</passphrase>
  13. </server>
  14. </servers>
  15. ...
  16. </settings>
Note that if you are connecting to an openssh ssh server which has the parameter "PasswordAuthentication" set to "no" in the sshd_confing, you will have to type your password each time for username/password authentication (although you can log in using another ssh client by typing in the username and password). You might want to switch to public key authentication in this case.
Care should be taken if using passwords in settings.xml. For more information, see Password Encryption.

How do I create documentation?

To get you jump started with Maven's documentation system you can use the archetype mechanism to generate a site for your existing project using the following command:
  1. mvn archetype:generate \
  2. -DarchetypeGroupId=org.apache.maven.archetypes \
  3. -DarchetypeArtifactId=maven-archetype-site \
  4. -DgroupId=com.mycompany.app \
  5. -DartifactId=my-app-site
Now head on over to the Guide to creating a site to learn how to create the documentation for your project.

How do I build other types of projects?

Note that the lifecycle applies to any project type. For example, back in the base directory we can create a simple web application:
  1. mvn archetype:generate \
  2. -DarchetypeGroupId=org.apache.maven.archetypes \
  3. -DarchetypeArtifactId=maven-archetype-webapp \
  4. -DgroupId=com.mycompany.app \
  5. -DartifactId=my-webapp
Note that these must all be on a single line. This will create a directory called my-webapp containing the following project descriptor:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>my-webapp</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11.  
  12. <dependencies>
  13. <dependency>
  14. <groupId>junit</groupId>
  15. <artifactId>junit</artifactId>
  16. <version>4.11</version>
  17. <scope>test</scope>
  18. </dependency>
  19. </dependencies>
  20.  
  21. <build>
  22. <finalName>my-webapp</finalName>
  23. </build>
  24. </project>
Note the <packaging> element - this tells Maven to build as a WAR. Change into the webapp project's directory and try:
  1. mvn package
You'll see target/my-webapp.war is built, and that all the normal steps were executed.

How do I build more than one project at once?

The concept of dealing with multiple modules is built in to Maven. In this section, we will show
how to build the WAR above, and include the previous JAR as well in one step.
Firstly, we need to add a parent pom.xml file in the directory above the other two, so it should look like this:
  1. +- pom.xml
  2. +- my-app
  3. | +- pom.xml
  4. | +- src
  5. | +- main
  6. | +- java
  7. +- my-webapp
  8. | +- pom.xml
  9. | +- src
  10. | +- main
  11. | +- webapp
The POM file you'll create should contain the following:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.mycompany.app</groupId>
  8. <artifactId>app</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>pom</packaging>
  11.  
  12. <modules>
  13. <module>my-app</module>
  14. <module>my-webapp</module>
  15. </modules>
  16. </project>
We'll need a dependency on the JAR from the webapp, so add this to my-webapp/pom.xml:
  1. ...
  2. <dependencies>
  3. <dependency>
  4. <groupId>com.mycompany.app</groupId>
  5. <artifactId>my-app</artifactId>
  6. <version>1.0-SNAPSHOT</version>
  7. </dependency>
  8. ...
  9. </dependencies>
Finally, add the following <parent> element to both of the other pom.xml files in the
 subdirectories:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <groupId>com.mycompany.app</groupId>
  7. <artifactId>app</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. ...
Now, try it... from the top level directory, run:
  1. mvn verify
The WAR has now been created in my-webapp/target/my-webapp.war, and the JAR is included:
  1. $ jar tvf my-webapp/target/my-webapp-1.0-SNAPSHOT.war
  2. 0 Fri Jun 24 10:59:56 EST 2005 META-INF/
  3. 222 Fri Jun 24 10:59:54 EST 2005 META-INF/MANIFEST.MF
  4. 0 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/
  5. 0 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app/
  6. 0 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app 
  7. /my-webapp/
  8. 3239 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app
  9.  /my-webapp/pom.xml
  10. 0 Fri Jun 24 10:59:56 EST 2005 WEB-INF/
  11. 215 Fri Jun 24 10:59:56 EST 2005 WEB-INF/web.xml
  12. 123 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app 
  13. /my-webapp/pom.properties
  14. 52 Fri Jun 24 10:59:56 EST 2005 index.jsp
  15. 0 Fri Jun 24 10:59:56 EST 2005 WEB-INF/lib/
  16. 2713 Fri Jun 24 10:59:56 EST 2005 WEB-INF/lib/my-app-1.0-SNAPSHOT.jar
How does this work? Firstly, the parent POM created (called app), has a packaging of pom and a list of modules defined. This tells Maven to run all operations over the set of projects instead of just the current one (to override this behaviour, you can use the --non-recursive command line option).
Next, we tell the WAR that it requires the my-app JAR. This does a few things: it makes it available on the classpath to any code in the WAR (none in this case), it makes sure the JAR is always built before the WAR, and it indicates to the WAR plugin to include the JAR in its library directory.
You may have noticed that junit-4.11.jar was a dependency, but didn't end up in the WAR. The reason for this is the <scope>test</scope> element - it is only required for testing, and so is not included in the web application as the compile time dependency my-app is.
The final step was to include a parent definition. This is different to the extend element you may be familiar with from Maven 1.0: this ensures that the POM can always be located even if the project is distributed separately from its parent by looking it up in the repository.