Tuesday, December 25, 2012

Define Solr Home Directory

DEFINE SOLR HOME DIRECTORY


If you want to run the solr server at the specified path you should introduce to your system such as server parameter.Solr home is the folder place that contains bin, conf, data folders and solr.xml. In tomcat eclipse environment
1 ) Double click to the server in servers tab
2 ) Then click to the Arguments tab
3 ) Put your config parameter such as -Dsolr.solr.home=D:\apache-solr-3.6.0\example\solr

(This is the folder that your solr configuration is handled)

4 ) Restart your server. Now the path in config parameter is working.

Solr Index File Location

HOW TO CHANGE THE INDEX FILE LOCATION OF SOLR

If you want to use your solr in a specified index folder, you should arrange a directory. For example : There is a solrconfig.xml file in the root of your solr server and you can see the related xml such as :  <dataDir>${solr.data.dir:}</dataDir> this means the directory path will be handled at the start up time of your server. This parameters default is the data directory that is in your example folder. If you want to specify a new folder you can define as server parameter. 

1 )I was using eclipse and tomcat so click twice to the server in your server tab.

2 ) Then click to Open Launch Configuration

3 ) Then click to the Arguments

4 ) Then put -Dsolr.data.dir=D:\solrIndex this if you want to store your index file at the D:\solrIndex folder. Then stop your server if it is running and then start again.

Now your index folders and index files will be created in the solrIndex folder.


After you change the home location of the solr, restart your solr.

To achieve this go to your solr home directory from command line that contains start.jar and then type java -jar start.jar. Then use it from your program if you develop web based restart your server with the configured server parameters.

Solr Eclipse Installation and Solrj Briefly

     SOLR INSTALLATION AND USAGE BRIEFLY

   Solr is a standalone server that makes all the indexing works and that is related with your data which will be examined in searching.
   Briefly : In a java program you will create a document from your object in your program and you will send it to your solr engine. Solr will get this information to its own indexing files. Then you can query, add new, update the existed, delete the documents that are in the solr. These processes can be done using solr user interface or programmatically from Java with solrj. In the first strategy if you use the user interface of the solr, you will realize that after querying the results will be returned as XML. If you pay attention to the url this operations have special urls. That you can also use this functionality if you do not want to use solrj. However solrj is easy to deal with the data that are returned by the solr. The Solr XML has two sections, the first part and the second part. The data that you send for the indexing will be kept in the second part. This is the brief description of Solr as far as i used. Of course it has much more usage areas and strategies.

First of all we need to set up the solr environment.
To start this download the solr from this url
I downloaded the Apache Solr 3.6.0d when i set. After you download extract in one of your directory i put it to D:\apache-solr-3.6.0 there will be some folders and files you will see.
Secondly
open your eclipse and create a new project i created Dynamic Web Project.
Add these libraries into your classpath - lib

Thirdly
Open your solr folders again. In your solr folder there will be a example folder, there is solr folder. This folder will be your example solr folder.
In this folder you will see bin, conf, data and solr.xml. The data folder contains your indexes. Conf folder contains files about your solr configuration.

Then open a command line and go to your solr../example directory from the command line and type java -jar start.jar  Then you will see the running of the solr server. Then open this url from your browser http://localhost:8983/solr/ after successful go to the Solr Admin then you can make your queries from your solr user interface.


Using solr from java is the SOLRJ.

Lets code the project that we opened at step two.

            HttpSolrServer httpSolrServer = new HttpSolrServer("http://localhost:8983/solr/");
    SolrInputDocument doc1 = new SolrInputDocument();
   
    doc1.addField( "id", "1", 1.0f );
   doc1.addField( "name", "can", 1.0f );
   doc1.addField( "price", 1000 );
   Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
   docs.add( doc1 );
   httpSolrServer.add( docs );
   httpSolrServer.commit();
   UpdateRequest req = new UpdateRequest();
   req.setAction( UpdateRequest.ACTION.COMMIT, false, false );
   req.add( docs );
   UpdateResponse rsp = req.process(httpSolrServer);
   
   SolrQuery query = new SolrQuery();
   query.setQuery("id:*");

   query.setHighlight(true).setHighlightSnippets(1); 
   //httpSolrServer.deleteByQuery("id:*",11);
   QueryResponse queryResponse = httpSolrServer.query(query);
   Iterator<SolrDocument> results= queryResponse.getResults().iterator();

   while (results.hasNext()) {
     String id = (String) results.next().getFieldValue("id");
   }



In the code above we created a document and added to the docs and then we created a query that we for the all ids and get response from the result of query is taken by the field values. If you want to delete the all the records that includes id field uncomment the line below from code.

     //httpSolrServer.deleteByQuery("id:*",11);

the 11 is the ms that this action will be committed

You can also rollback the operations with the code below
     httpSolrServer.rollback();


Java Timing Functions

                         HOW TO USE JAVA TIMER

Java Timer tasks are the scheduled tasks for the program, they are intented to be executed on a specific interval of times or on a specific time  such as this :

There is a Timer class that we will create and it will contain a class to be executed in a specific intervals.

Timer timer = new Timer();
timer.scheduleAtFixedRate(new Go(), 0,20000);

first we created timer and we attached a schedule that is 20000 ms will be 20 seconds to the Go class.
Go class is special because it is extends the TimerTask which will have a function called run()

public class Go extends TimerTask{

        public void run(){
        //This code will be run
}
}

also you can define a delay time before execute in schedule through this parameter
timer.scheduleAtFixedRate(new Go(),DELAY,20000);

Thursday, December 13, 2012

Android Menu Example

    ANDROID MENU EXAMPLE

(This example includes basic menu example)

    We will create a menu button for the Android 2.2 Froyo in this example. You can also develop for the Android 2.2 Froyo and you can use this menu at Android 2.3 and lower versions of  the android properly.
    After the android 3.0, the menu button is deprecated but many people using android now also have lower versions.
1 ) Context menu : When you click on a link as long press. You will see some choices on the screen this is the context menu.
2 ) Pop up menu : If you see in a faded screen as list this will be the pop up menu.
    DEFINING A MENU IN XML
    You should define your menu items at the xml as developer-android.com says. You can also create your list in your java code. You can then get this xml as Menu object with inflating.
    You can use your res/menu folders for this xml. Create a new xml named as customize_menu.xml
    Example xml is such below :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
      <item
        android:id="@+id/menu_settings1"
        android:title="@string/menu_settings"
        android:checkable="true"
        android:menuCategory="container"
        android:titleCondensed="@string/app_name"
        />
   
        <item
        android:id="@+id/menu_settings2"
        android:title="@string/menu_settings"
        android:checkable="true"
        android:menuCategory="container"
        android:titleCondensed="@string/app_name"
        />
        <item
        android:id="@+id/menu_settings3"
        android:title="@string/menu_settings"
        android:checkable="true"
        android:menuCategory="container"
        android:titleCondensed="@string/app_name"
        />

</menu>
And also in your activity class you can code as
@Override
        public boolean onCreateOptionsMenu(Menu menu) {
               
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.customize_menu, menu);
                return true;
        }
    For more, you can change your list order with the attribute of
   android:orderInCategory="Number"
    for example if you define your android:orderInCategory in one item as 100 it will be in the 100th order.

    You can also change your contents of the menu items programmatically. For example changing the all of the menu items titles that helped me http://stackoverflow.com/questions/6150080/set-a-menu-item-as-checked-from-code

After you run this application you must get this screen as in Picture 1
Picture 1


package com.example.menuexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tV = (TextView) findViewById(R.id.can);
tV.setText("Menu Example");
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
   super.onPrepareOptionsMenu(menu);
   menu.findItem(R.id.menu_settings1).setTitleCondensed("menu1");
   menu.findItem(R.id.menu_settings2).setTitleCondensed("menu2");
   menu.findItem(R.id.menu_settings3).setTitleCondensed("menu3");
   return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.customize_menu, menu);
return true;
}
}


This is the java codes related with menu. onPrepareOptionsMenu gives you the opportunity to manipulate the id based resources. You can not manipulate the menu in onCreateOptionsMenu because inflater has not been finished yet so you would crash with the null pointers.
Also there is super tutorial that is suitable for advance customization



Android Programming Introduction


    ANDROID PROGRAMMING - INTRODUCTION

    Android that is mobile platform that gives us the possibility of developing through the Java programming language. It can also be developed with another languages but the most used one is i think Java J I will tell you the android structure from the point of programming below.
    If you developed java web applications before it is easy to learn android structure but if not maybe it is hard at the beginning after some time it will be easy do not worry.
    There is a project folder with the following sub folders
Src : that has a package of java files that are developed by you. Your java program will be in this folder.
Gen:that folder has a special file named as R.java that is created for your indexes and should not be changed manually. The program creates and updates at the build times.
Androidx.y library : Android has lots of versions such as 2.2, 2.3, 2.4... and you should choose the version of the android before you create the project.
Assets : You can store your special files in there such as your text files, xml, fonts musics and video...
Bin : it contains your projects .apk file that you can use in mobile for installing.
Res
                ร drawable-hpdi
                ร drawable-lpdi
                ร drawable-mpdi
                ร drawable-xhdpi
                ร layout
                ร menu
                ร values
                ร xml
The drawable-x files above includes images that your program uses. Layout folder contains your activites layouts. Menu folder contains menu items xml files. Values folder contains the value files such as the equations of the strings this is equivalent of the application.properties file on struts :) . Xml folder contains the specialized xml such as for some utility development tools.
AndroidManifest.xml
Android Manifest : this is the most important file in the project. It contains all the activites, services that will run at work. Also it includes all necessary permissions and some limitations such as device screen and also the supported sdk versions.


At the Java Side you should know these
Activities :
Activities are the main building block for your application. Setting view to the device can be achieved by defining activity. To define Activity, you should implement Activity interface first then it needs some methods that i will explain, you need to Override them ;
protected void onCreate(Bundle savedInstanceState) {
this is the function of setting view to the screen. In this function your program will have road. You need to set your content view from xml to the screen or you can create your own layout programmatically from Java code.  And also there is one more function
public boolean onCreateOptionsMenu(Menu menu) {
This is the basic menu function that you can get your menu to the screen. Building menu is in another post.

When you open a new android project, you will have a default Hello World project that you can trace.

Send Data From Jsp To Servlet

                    SEND DATA FROM JSP TO SERVLET

                                   How to send data from Servlet to Jsp page
    Now we will learn how to send user data to servlet.This is easy but it is useful for lots of situations. In Jsp page we can get user data in many ways and we can pass data to servlet again in many ways. One of them is to send with form. To use form we should have some knowledge about html forms.
Html Forms :
    <form> is the root tag. This tag has some attributes for example some of them:
Action : you can put your servlet name to here if you want to pass data to servlet or you can put here struts action that will be in another page.
Method : there is 2 methods to send data to servlet. One of them is the get and the other is the post. If you select get method you can see your data from url. If you send as post you can not see your data in url. This is more secured. When you are programming to send data to another phase get methods gives you some flexibility about adding extra data. Of course you can add extra data with post method but you should use a little bit more advanced javascript.
    <input> : this tag can be used as container for the user data. You can get user data with this tag. This tag has one attribute that is very useful at the servlet part.
Name : whatever you write to here you can get this value with the same name at the servlet side.
Type: To achieve the sending data you need to use button you can define them with this attribute.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form</title>
</head>
<body>
<form action="servlet" method="get">
       <input name="field1"></input>
       <input name="field2"></input>
       <input name="field3"></input>
       <input type="submit"/>
</form>
</body>
</html>

Servlet code is :


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class servlet
 */
public class servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String str = request.getParameter("field1");
String str2 = request.getParameter("field2");
String str3 = request.getParameter("field3");
out.println("You typed : "+str+"\n"+str2+"\n"+str3);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("DoPost");
}

}


Picture 1

Picture 2
You can see the url contains data that the user can see.




Servlet Mapping

                               SERVLET MAPPING

    You can reach to your servlet class from url with the mapping information. If you give url mapping to your named servlet in web.xml file and if this named servlet is related with the real path in web.xml then you can write custom url to the browser and you can reach also you can type it in your program as variable.


    For example you opened a servlet in com.example as exampleServlet and you want to make it associated with the http:/...:../ProjectName/{MyCustomServletName}
You should open your web.xml and
<servlet>
       <description>
       </description>
       <display-name>exampleServlet</display-name>
       <servlet-name>exampleServlet</servlet-name>
       <servlet-class>com.example.exampleServlet</servlet-class>
  </servlet>
    This will introduce your servlet to the web application.
<servlet-mapping>
       <servlet-name>exampleServlet</servlet-name>
       <url-pattern>/exampleServletNow</url-pattern>
</servlet-mapping>
    This maps your url pattern with the servlet name defined as index in web.xml and this index goes into <servlet> tags and searches the same of it. When the search results successfully it returns the servlet-class that gives you the exact builded class to your browser.If your project name is DynamicWebExample
Then you can type as http:/localhost:8080/DynamicWebExample/exampleServletNow or whatever you wrote for mapping information.

Web xml Filtering

                WEB.XML FILTERING EXAMPLE

    Filtering is related with pre-processing. Before you go into your page you can do manipulation with your data. This mapping is defined in web.xml file of your project. And you can open a java file at the appropriate package with the suitable interface and you must implement its methods correctly. For example :

<filter>
  <filter-name>coding</filter-name>
  <filter-class>com.example.code.Coding</filter-class>
  <init-param>
   <param-name>coding</param-name>
   <param-value>ISO-8859-1</param-value>
  </init-param>
 </filter>
<filter-mapping>
        <filter-name> coding </filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

     You can declare your filter that you use for the pre processor for your each request for example in Struts framework if you have an action mapping for the path of url, you can jump into the filter before action class. For example in this example code for each request with any of the url parameters get into the filter name and this filter name maps the action to the filter class that you can pre process somethink before action. Your filter class in the appropriate package implements Filter as in the example code below.

package com.example.code;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Coding implements Filter{

       @Override
       public void destroy() {
              // TODO Auto-generated method stub
       }
       @Override
       public void doFilter(ServletRequest arg0, ServletResponse arg1,
                     FilterChain arg2) throws IOException, ServletException {
              // TODO Auto-generated method stub
              System.out.println("Now in Filter You can Pre process in here");
              arg2.doFilter(arg0, arg1);
       }
       @Override
       public void init(FilterConfig arg0) throws ServletException {
              // TODO Auto-generated method stub
             
       }
}
For example if you start your server and go into one of your page from url you can see from console the result of test.

Wednesday, December 12, 2012

WHAT IS WEB.XML FILE

WHAT IS WEB.XML FILE 

PART 1

Most of the dynamic web projects contains dynamic web x ml files to define your projects (big picture). Some of them has this file contents as annotations.
For example the default one is
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
       <display-name>DynamicWebExample</display-name>
       <welcome-file-list>
              <welcome-file>index.html</welcome-file>
              <welcome-file>index.htm</welcome-file>
              <welcome-file>index.jsp</welcome-file>
              <welcome-file>default.html</welcome-file>
              <welcome-file>default.htm</welcome-file>
              <welcome-file>default.jsp</welcome-file>
       </welcome-file-list>
</web-app>
    In the first row the x ml version is defined. This x ml version and encoding type is related with the web x ml own not for the project.
    Root of the web x ml file is the <web-app that has id, version and namespaces.
    <displayName> is the name of your project.

    <welcome-file-list> tag includes one or more <welcome-file> tags which contain some files related with welcome. If you want to reach to the project with the project name url such as http:/localhost:8080/DynamicWebExample you can see the welcome file. If there is not a welcome file in project that was defined in web.xml file, web.xml file gives the another one from the order to project so the files in welcome-file-list is processed in the order of the list. If you type as http:/localhost:8080/DynamicWebExample then you can see the picture 2.
Picture 1
Picture 2



The other property that i will explain is the <jsp-property>
<jsp-config>
              <jsp-property-group>
                     <description>To Encode With Utf8</description>
                     <url-pattern>index*.jsp</url-pattern>
                     <page-encoding>UTF-8</page-encoding>
              </jsp-property-group>
</jsp-config>

    If you want to make some pages encoding specialized you can use this method. For example the code above forces the user to encode index,index1,indexa,indexq… etc files in UTF-8 so if you encode this files different from this encoding type you will get error while testing such as :
org.apache.jasper.JasperException: /index.jsp(1,1) Page-encoding specified in jsp-property-group (UTF-8) is different from t…

This error causes from the jsp that was defined as : 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding"ISO-8859-1"%>
    so if you change the pageEncoding to UTF-8 then you can test it correctly. But now the utf characters will come as iso type and such as ? so if you change also the charset to UTF-8 you can see the page correctly typed. Such as for the Swedish characters WELCOME รถ now you can test.

       If you can not see your own characters even after changing the encoding you can change your tomcat language that I will explain how to do this later.

    You can also avoid your errors from user with this code
<error-page>
       <exception-type>java.lang.ClassNotFoundException</exception-type>
       <location>/hello.jsp</location>
</error-page>
    If you encounter with the exception type that is class is not in the project or not on the path is given, you can route your web to specialized files.
<error-page>
       <error-code>404</error-code>
       <location>/hello.jsp</location>
</error-page>
You can also code such as above. This is not the same with the first one(!).
<icon>
              <large-icon></large-icon>
</icon>
You can also define your application icon with the code above.
Configuration tags will continue…