Monday, 22 October 2018

Show / Print a variable value in input type field in Servlet.

Generally in Servlet we use HTML in Java (Java --->HTML), but in above we have to write Java ----> HTML -----> Java. So, we can write this in following manner

A simple Sevlet code can be like -

out.println("<table border='1' cellspacing='3' cellpadding='2'>");

If we want double quote instead of single quote in HTML properties value then code will be -

out.println("<input type=\"hidden\" name=\"place\" value=\"any value\">");

And finally when we want any variable value in value property of input type, then code will be -

out.println("<input type=\"hidden\" name=\"place\" value=\""+ variable +"\">");

Saturday, 20 October 2018

Make back button working in action bar in Android.

Recently I was trying to use working back button on my one of the project, but whatever I was done previously was not working. It was a crash every time with error message -


I am newbie to Android, but I was done back activity few day back but after updating my Android Studios and APIs nothing was working. I was also uses  inflated menu in my project, and debugger always stuck in onOptionsItemSelected(MenuItem item) method which I was used for option menu. I also tried many unsuccessful lines of code. Finally I got this solution for my problem -

1 .  In  onCreate(Bundle savedInstanceState) method use -

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

2 .  Override methos in your activity class

@Overridepublic boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}


3 . In onOptionsItemSelected(MenuItem item) method use -

switch (item.getItemId()) {  
       case android.R.id.home:
        Intent i = new Intent(this, Your_Parent_Activity.class);
        intent.addFlags(i.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        return true;
}


Monday, 8 October 2018

File listing and download using hyperlink in JSP from any folder.

Why I am writing this blog? In network some times we don't have server/FTP server(I personally think that it is not more interactive, i.e it can't be in a form of web page) and we have to share any file/s to more than 50 people, then we stuck in messages like "No more connections can be made.. bla bla bla" or either network restriction policy don't allow to do so. Apart from this there may be other issues that can stop to access shared folders in network. I have seen all these kind of problem in accessing shared documents.

So I tried to make web page like application where user can view and download their files via web page. For that you require obviously Tomcat Server for running JSP pages.

So, you should have working knowledge of Tomcat Server.

Create a JSP page and save in your project directory and use this code.

   <p><% 
File folder = new File("G:\\tomcatserver\\webapps\\softshare\\share\\fonts");
File[] listOfFiles = folder.listFiles();
%><table><%
     for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
String pp="share/fonts/"+listOfFiles[i].getName();
%><tr><td width="500px"><a href="<%=pp%>"><%=listOfFiles[i].getName()%></a><%
   %></td><td><%
Path path=Paths.get(listOfFiles[i].getPath());
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
out.println(attr.creationTime().toString().substring(0,10));
out.println(" </td></tr>");
      }
    }
%></table><%
 %></p>

Now lets see the code in details-

File folder = new File("G:\\tomcatserver\\webapps\\softshare\\share\\fonts"); //path of folder
File[] listOfFiles = folder.listFiles(); // will store file in array.

This code will read the files of fonts/ folder. The font folder should be in your project directory, it should not be out your tomcat server.

 String pp="share/fonts/"+listOfFiles[i].getName();

pp will store the relative path of files.

Now you will be able to list and download your file via hyperlink.

Thursday, 4 October 2018

Add app bar / action bar / tool bar and menu in Android Studio.

App bar or action bar or tool bar is a dedicated bat on the top of the every app/activity. It is also called title bar of activity. It may contain toolbox/icon or overflow menu or can be both.


So how can we create this action bar in your project?

1. create menu.xml file in res/menu directory of your project. To create go to -

New ---> Android Resource File

Enter the file name (should start with small letters alphabets) then select resource type as menu then click Ok.


Now create menu by adding items in this menu.xml file.

<item android:title="Item 1"></item>
<item android:title="Item 2"></item>
<item android:title="Item 3"></item>
<item android:title="Item 4"></item>

The complete menu.xml is-

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:title="Item 1"></item>
    <item android:title="Item 2"></item>
    <item android:title="Item 3"></item>
    <item android:title="Item 4"></item>
</menu>


2. After creating menu, you require it to inflate on title bar/action bar. To inflate, write given below code in you activity

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater in=getMenuInflater(); in.inflate(R.menu.menu,menu); return super.onCreateOptionsMenu(menu); }

After running your program you can see the menu in action bar, when you click on three dots on left side of action bar like -


If you want to add icon or tool box on the action bar then in menu.xml file, use icon property of item tag and select any .png image from your res/mipmap directory, like (You can see home icon in screen shot given below)  

<item android:title="home"    android:icon="@mipmap/home"    app:showAsAction="always"></item>




Error: Cannot fit requested classes in a single dex file (# methods: 87573 > 65536) When you try to generate apk in Android Studio 3.2

After updating my Android Studio from 3.0.1 to 3.2 and today when I tried to generate apk to run my project in my android phone, I stuck on error:-

"Error: Cannot fit requested classes in a single dex file (# methods: 87573 > 65536)"

After searching on internet I found this working solution for me.

Let see the screen shot -



To resolve this -

Go to app level build.gradle and add this dependency under dependencies { }

implementation 'com.android.support:multidex:1.0.3'

also add this line in defaultConfig { } section

multiDexEnabled true 




and then click sync now.



Now your problem is resolved.

Sunday, 30 September 2018

How can you change an activity title in Android?

Sometimes when we create an activity in Android we don't put appropriate title of activity or may be later on we want to change the activity title. So how can we change it? Let see -

There are two ways to do this.

1. Using Java code
2. Change in XML file

Using Java code-

 setTitle("Your Title");

put this code in activity Java coding page, like-

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle("Your Title");

Another way to do this is to change in AndroidManifest.xml file of your project. See the screen shot to locate AndroidManifest.xml


You can see your activity in this file under <application></application> tag. You just have to change/enter the label of your activity.

android:label="Your Title"
  
See bellow- 

<activity android:name=".Your_Activity"    android:label="Your Title">
</activity>

Thursday, 27 September 2018

Run your first Jython page on Apache Tomcat Server

What is Jython? 
Jython is a Java implementation of Python that combines expressive power with clarity. Jython is freely available for both commercial and non-commercial use and is distributed with source code. Jython is complementary to Java and is especially suited for the following tasks:
  • Embedded scripting - Java programmers can add the Jython libraries to their system to allow end users to write simple or complicated scripts that add functionality to the application.
  • Interactive experimentation - Jython provides an interactive interpreter that can be used to interact with Java packages or with running Java applications. This allows programmers to experiment and debug any Java system using Jython.
  • Rapid application development - Python programs are typically 2-10X shorter than the equivalent Java program. This translates directly to increased programmer productivity. The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products.
                                               As described at https://wiki.python.org/jython.

Jython is the best choice if you have already developed applications in Java. However many developer/programmer feel that it is slower than Java because it is interpreted and consume more resources and many other issues, but I don't want to discuss it here.

Let see how we can run Jython on Tomcat server.

Note :- I have used Windows Server 2016, Java SE 10.0.2 and Apache Tomcat 9.

Pre-requisite :- 
  • Download Java from here.
  • Download Jython from here.
  • Download Apache Tomcat from here. 
After downloading these three install it. You can install Java just double clicking on it as normal software installation in Windows.


After installing Java set JAVA_HOME, PATH and CLASSPATH environment variables in your system for running Java, Jython and Servlets.
For setting environment variable, go to This PC/My Computer on your desktop, right click and then go to Properties 


Click on Advanced system settings


Then click on Advanced tab and then Environment Variables


Click on New button. In Variable name input field enter variable name JAVA_HOME and
variable value C:\Program Files\Java\jdk-10.0.2; (path of your jdk home directory) (After Java Installation)

Again click on New and put the variable name CLASSPATH and value will be  like C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib\servlet-api.jar; for running Servlet. (After Tomcat Installation to test of running servlet)

Not required for running Jython on web, skip this:- [You should also add java and jython (after installation of Jython) path for running java command from anywhere. To do this click on Path variable then click on Edit button then click on New and add just put C:\Program Files\Java\jdk-10.0.2\bin for running Java and for C:\jython_2.2.1 (path of your jython home)]

You can see all values after setting this the screenshot below.




After finishing all Java related settings, now install Jython. After downloading Jython you can see that it is a jar file, so go to Download folder where you have downloaded it using command prompt.
And run command

java -jar jython_installer-2.2.1.jar

Jython installation GUI will open and just install it.


After installation of Jython, install Apache Tomcat and check it by typing http://localhost:8080/ in any of your favorite browser. If you see page like given below, then it is working.


Now you have done all setup for your first Jython application.

Create a directory myfirstjython in webapps  directory. Also create WEB-INF directory and in WEB-INF create a directory classes and lib and a xml file web.xml. So, you WEB-INF directory will look like -


To test that our every set up is working properly, we will run a Servlet on this server.

So write your servlet like-



import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyFirstServlet extends HttpServlet {
public void doPost (HttpServletRequest request,
   HttpServletResponse response)
throws ServletException, IOException {
response.setContentType ("text/html");
PrintWriter toClient = response.getWriter();
toClient.println ("<html><head><title>My First Servlet</title>" +
  "<body><h2>My First Servlet</h2></body></html>");
}
}


compile it on command prompt by running

javac MyFirstServlet.jar

If there is no error. Open web.xml file and deploy here your Servlet by editing this file as -


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">
   <servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>MyFirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/MyFirstServlet</url-pattern>
</servlet-mapping>

</web-app>

Restart your Tomcat Server and then run Servlet on browser by typing-

http://localhost:8080/myfirstjython/MyFirstServlet

 Now after running Servlet, You are ready to run your first Jython program on web.

So, first write your Jython program to run on web. Here is a Jython program that is equivalant to above Servlet -

from javax.servlet.http import HttpServlet

class MyFirstJythonServlet (HttpServlet):
def doGet(self,request,response):
self.doPost (request,response)

def doPost(self,request,response):
toClient = response.getWriter()
response.setContentType ("text/html")
toClient.println ("<html><head><title>This is my first Jython.</title>" +
  "<body><h1><center>This is my first Jython.<center></h1></body></html>")


And save this file to your web root directory.

Now in web.xml (projectfolder/WEB-INF/web.xml) do the following entry.

 <servlet-name>PyServlet</servlet-name>
  <servlet-class>org.python.util.PyServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>PyServlet</servlet-name>
<url-pattern>*.py</url-pattern>
</servlet-mapping>

If you change web.xml file, you will require to restart tomcat server every time.
Now restart your Tomcat Server and open any browser and type -

Servlet requires every time to compile after every change in file, while Python does not require.
 
http://localhost:8080/jythondemo/MyFirstJythonServlet.py

If all is right, output will be -


The complete web.xml file is -

 <?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
  
  <servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>MyFirstServlet</servlet-class>
</servlet>
<servlet>
  <servlet-name>PyServlet</servlet-name>
  <servlet-class>org.python.util.PyServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/MyFirstServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>PyServlet</servlet-name>
<url-pattern>*.py</url-pattern>
</servlet-mapping>

</web-app>

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...