Wednesday, 3 October 2018

Sending Ajax request to server and receive output

For e.g you have a select box and on selection of a specific option you have to send ajax request for fetching some information in our case we are validating information on server side and returning corresponding response.

1) include libraries
<script type="text/JavaScript" src="../Javascripts/ajax.js"></script>

2) Create javascript function

function loadInstallmentOptions(objValue){
if(objValue==<%=SOMECONSTANT%>){
var billCodeId = document.getElementById("Id").value;
var url='validateDetails.jsp?Id='+Id;
ajaxCallSite = new sack();
ajaxCallSite.requestFile = url;
ajaxCallSite.onCompletion = function(){responseOfValidation(ajaxCallSite);};
ajaxCallSite.runAJAX();
}else{
document.getElementById("element1").value="0";
document.getElementById("element2").value="";
document.getElementById("element3").checked=false;
document.getElementById("element4").style.display="none";

}
}

3)  in forwarded jsp do the calculation and send response in JSON using

JSONObject AmountHolder = new JSONObject();
showControls = your business logic response;
maxAllowed = your business logic response;
AmountHolder.put("showControls",showControls);
AmountHolder.put("maxAllowed",maxAllowed);
AmountHolder.put("providedValueIsGreater",providedMaxInstallment>maxAllowed);
response.getWriter().write("("+AmountHolder.toString()+")");
response.getWriter().close();


4) On response do the action

function responseOfValidation(ajaxCall)
{ 
responseObj=eval(ajaxCall.response);
var showControls=responseObj.showControls;
if(showControls==true){
document.getElementById("elementControls").style.display="block";
}else{
document.getElementById("element1").value="0";
document.getElementById("element2").value="";
document.getElementById("element3").checked=false;
document.getElementById("element4").style.display="none";
}
}

Mocking

Case: I have a class which uses Autowired on two different classes objects. I have to unit test methods of this class but the methods uses calling to object's methods to perform some operation inside those methods that i want to test.
Therefore, i need to mock the calling of those methods and return something that mock the values and test the rest of the operation. What dived me into struggle that whenever i try to mock those field injection it throws me some sort of error related to Mock method invocation.

Solution:
Firstly, we need to annotate the test class with @RunWith(MockitoJUnitRunner.class) this annotation will help us to initialize the fields annotated with @Mock annotations.

Also we need to use the MockitoAnnotations.initMocks(this) though we can use any of them but in my case it does not seem to be working when removing the @RunWith annotation it throws me Assertion Error (it can be because of the fact that i am testing a VOID function by try catch and Assert.assertTrue). However, the main purpose of the @RunWith annotation is keep tests clean and improves debugging experience.

Second step is to Mock the declaration of the Autowired class attributes and use @InjectMocks on the class that contains the methods you want to mock. (@InjectMocks is used on the field which injection should be performed your private fields)

Third step is to use MockitoAnnotations.initMocks(this) in @Before method. Also, you can specify the mocking logic in this method if the logic repeats itself.

Fourth is to Mock the object's method call such as Mockito.when(firstMockedObject.someMethod(anyArguments)).thenReturn(yourMockedObject)
for e.g see: dzone.com/articles/use-mockito-mock-autowired

We generally use mock when we want to mock whole object's behavior while using spy we will be spying or stubbing specific methods of it. So Mock acheives full mocking and Spy acheives partial mocking.

EXPECTED EXCEPTION
when declaring the ExpectedException it should be declared as public otherwise it won't work


AssumptionViolationException 

An exception class used to implement assumptions. Assumption is a state in which a given test is meaningful and should or should not be executed. A test for which an assumption fails should not generate a test case failure.

MAVEN: Copy test resources from on project to another

CASE: I have two projects A and B, project A has lots of csv files in its src/test/resources folder which project B wants to use in its application. Though it is not an ideal case when a test resources becomes a liablity of some other projects source folder. But we have this case. However, we can use these files in our test classes as well.

SOLUTION:

In project A where the csv files are present you have to make those files compiled in a jar and shared them across in the project B. There are other apporaches as well but this one seems to be working for me till now. Others are usefull when you have to share the resources NOT from the test folder but from the source folder.

Anyway, you have to define the following in the project A pom.xml

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
<executions>
 <execution>
<goals>
                <goal>test-jar</goal>
            </goals>
</execution>
</executions>

</plugin>
</plugins>
</build>

The above code will make snapshot/jar with suffix -tests which will use as classifier afterwards.

In Project b pom.xml you can use the maven dependency-plugin to extract files from jar:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>unpack</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>yourSourceGroup</groupId>
                                <artifactId>yourSourceArtifact</artifactId>
                                <version>1.0.0</version>
                                <type>jar</type>
                                <includes>path/to/Files.whatsoever</includes>
                                <outputDirectory>${project.build.directory}/your/target/folder</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

MAVEN: TO RESTART THE SERVER IN OUR CASE JBOSS THROUGH MAVEN

Normally org.wildfly.plugins provide wildfly-maven-plugin with some basic preinstalled commands that can be run direcly through maven scripts such as deploy,redeploy, run, start, shutdown etc. (For more see docs.jboss.org/wildfly/plugins/maven/latest/plugin-info.html). What I want to accomplish is to restart the jboss application server by running one command the fun part is the server is located somewhere else.

However, first hurdle was to ensure either we can restart the server, for this, i put aside the externel server thing for later and tried to restart the local one. As one can see the Shutdown has an optional parameter for reload, what more i have used is jboss-home because when i was trying to start the server it was using the server that was reside in my deployed project war some other location that i do not want to use.

Therefore, i provided the particular JBOSS directory in the configuration along with the shutdown parameter to let the wildfly knows i want to restart the server not shutdown. Following is the code that i have used:

<plugin>
<groupId>or.wildfly.plugin</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>1.2.1.Final</version>
<configuration>
<jboss-home>C:/.../jboss-eap-7.0</jboss-home>
<reload>true</reload>
<hostname>127.0.0.1</hostname>
</configuration>
</plugin>

The above code helped to restart my local server with the wildfly:shutdown command.


How to get Properties (key,value) from pom.xml in your java file





The scenario was related to put the integration test server credentials such as server url, server url, username and password in pom.xml and to call them in your java class such as Junit test. The test used the credentials and call the web service.




FileReader reader = new FileReader("pom.xml");
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
Model model = mavenReader.read(reader);
Properties mavenProperties = model.getProperties();
String propertyValue = mavenProperties.getProperty("yourProperty");




On internet you may find something additional such as putting the File of POM.xml and setting it into the model and the creation of MavenProject. However, this works fine and returns all the required properties from the pom.xml.


In addition to this, we can also use the above code to fetch other POM objects such as dependencies, project name, version etc.



Tuesday, 8 August 2017

Handling Internet Explorer error "File couldn’t be downloaded" in J2EE application

This error was one of a stubborn errors due to insufficient and misleading information on the internet. On the face of it, the issue resembles with the IE settings. Furthermore, the file downloads when the application is access directly on server browser or other client browsers through FireFox, this issue appears on Chrome and IE 11.




 Initially, I found following as the solutions:
  • using a login with Admin rights
  • disabling download manager
  • disabling internet security or you antivirus
  • Windows Firewall On/Off
  • In-Activating the option "DO NOT SAVE ENCRYPTED FILES TO DISK " in internet explorer settings.
  • Messing with Windows Registry. For e.g. setting the value to 1 for ScanWithAntivirus at location HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Attachments
After trying all the option provided above and have no luck what it appeared to me that it is something with the response of the server that needs to be pushed. Once again I dived into the code which apparently looks OK to me initially. 


What flush() method do according to the Java documentation is : 

Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination. 

And the second paragraph that leads me to the conclusion of the solution:

If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive. 

What here is missing is close() method which ensures that the output stream is close and release any system resources with the stream. In documentation, it states,

Closes this output stream and releases any system resources associated with this stream. The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.

Therefore, following code fixes the problem:



P.S. For .net users the Response.End() should work. Any comments, related to this topic is highly appreciated which increases and helps the information of readers. Cheers.. 😃

Saturday, 4 May 2013

Tomcat – java.lang.OutOfMemoryError: PermGen space Cause and Solution

Add JAVA_OPTS in your catalina.bat or Catalina.sh

set JAVA_OPTS="-Xms1024m -Xmx10246m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"

PermGen Space of heap is used to store classes and Meta data about classes in Java. When a class is loaded by a classloader it got stored in PermGen space, it gets unloaded only when the classloader which loaded this class got garbage collected. If any object retains reference of classloader than its not garbage collected and Perm Gen Space is not freed up. This causes memory leak in PermGen Space and eventually cause java.lang.OutOfMemoryError: PermGen space. Another important point is that when you deploy your web application a new Clasloader gets created and it loads the classes used by web application. So if Classloader doesn't get garbage collected when your web application stops you will have memoery leak in tomcat.