Java Exercises

Palindrome Program

package com.effectivejava;
public class Palindrome {
    public static boolean isPalindrome(String word) {
       boolean isPalindrome = false;        
       String reverseWord = new StringBuilder(word).reverse().toString();        
       if (word.equalsIgnoreCase(reverseWord)) {
            isPalindrome = true;        
        }
        String newWord = "";        
        for (int i =word.length() -1; i>=0;i--) {
            newWord = newWord + word.charAt(i);        
        }
        if (word.equalsIgnoreCase(newWord)) {
            isPalindrome = true;        
        }

        return isPalindrome;    
    }

    public static void main(String[] args) {
        System.out.println(Palindrome.isPalindrome("Deleveled"));    
    }
}




POP3 and IMAP difference

https://www.jscape.com/blog/smtp-vs-imap-vs-pop3-difference

javax.xml.bind.UnmarshalException - with linked exception: [javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1] Message: Premature end of file.]

 javax.xml.bind.UnmarshalException
 - with linked exception:
[javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Premature end of file.]

You are getting the error because the InputStream has been advanced to the end during the output

Here is the code I used


xmlValidatorService.setOpsReport(false);List errorList = 
    xmlValidatorService.runValidation(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(WellsJaxb.class);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader
                                 (inputStream);
Unmarshaller um = jaxbContext.createUnmarshaller();
wellsJaxb = (WellsJaxb)  um.unmarshal(xsr);

org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at 534 5.7.9 https://support.google.com/mail/?p=WebLoginRequired v202-v6sm20135393oie.47 - gsmtp

org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at
534 5.7.9  https://support.google.com/mail/?p=WebLoginRequired v202-v6sm20135393oie.47 - gsmtp

Google prevent it for security purpose..
you will see turn off or turn on. Click "Turn on"
Then try your code again it will work, worked for me





org.xml.sax.SAXParseException; Element 'numAPI' has both a 'type' attribute and a 'anonymous type' child. Only one of these is allowed for an element.

org.xml.sax.SAXParseException; systemId: file:<: 21;
columnNumber: 56; src-element.3: Element 'numAPI' has both a 'type' attribute and a 'anonymous type' child. Only one of these is allowed for an element.


<xs:element type="xs:long" name="numAPI">  <xs:simpleType>    
<xs:restriction base="xs:long">      <xs:minLength value="1"/> 
   </xs:restriction>  </xs:simpleType></xs:element>


After the fix

<xs:element name="numAPI">  <xs:simpleType>    
<xs:restriction base="xs:long">      
<xs:minLength value="1"/>    </xs:restriction>  
</xs:simpleType></xs:element>

How to Use Quality of Service (QoS) to Get Faster Internet When You Really Need It

https://www.howtogeek.com/75660/the-beginners-guide-to-qos-on-your-router/

How to create a locking scenario with SQL Server DB and application


First switch off the Auto commit on SQL ServerMgmt Studio

Disabling Autocommit mode in SSMS

By default as we know SSMS (SQL Server Management Studio) is in a Autocommit mode, which means whenever a transaction is executed then that is committed by default. If we want to disable Auto commit mode in SSMSL, then follow below steps:
  1. Connect to SQL Server using SSMS
  2. From the Menu bar, select Tools –> Options
  3. Select Query Execution –> SQL Server –> ANSI
  4. Make sure that you check the check box SET IMPLICIT_TRANSACTIONS
  5. Click on OK
Now, open a new Query window and start executing the scripts.
Identify a record in the a table. Make sure that the data in this table is being used (update/delete/read (locked)) by the app
SELECT  * FROM dbo.true_r  where column1 = '123456' and id = 30059468;
update dbo.true_r set sect = 'SFC' where id = 30059468  and column1 = '123456';
if you now open up a new query window and execute the above select statement it would be hung.
Don't commit this transaction.
Now from the application perform the operation that tries to access the above record. You could see that the application is hung.
If you want to see the threaddump for linux
1.  ps -ef | grep JAVA


2. KILL -3
In major enterprises for security reasons only JREs are installed in production machines. Since jstack and other tools are only part of JDK, you wouldn’t be able to use jstack. In such circumstances, ‘kill -3’ option can be used.
kill -3 
Where:
pid: is the Process Id of the application, whose thread dump should be captured
Example:
Kill -3 37320
When ‘kill -3’ option is used thread dump is sent to standard error stream. If you are running your application in tomcat, thread dump will be sent in to /logs/catalina.out file.
Note: To my knowledge this option is supported in most flavors of *nix operating systems (Unix, Linux, HP-UX operating systems). Not sure about other Operating systems.
A good resource on threaddumps
https://dzone.com/articles/how-to-take-thread-dumps-7-options
Once you do the commit on the DB Query window, everything would be back to normal.









SQL Error: 0, SQLState: HY010, java.sql.SQLException: Invalid state, the Connection object is closed


SQL Error: 0, SQLState: HY010, java.sql.SQLException: Invalid state, the Connection object is closed

Solution:
I restarted the docker container to resolve this issue.

How to use JUnit with Apache Jmeter

  1. Write your JUnit test and jar the classes
  2. Copy and paste the jar files into jmeter/lib/junit directory
  3. Start JMeter
  4. Select Test Plan
  5. Right click Add → Thread Group
  6. Select Thread Group
  7. Right click Add → Sampler → JUnit Request
  8. Enter my unit test in the name
  9. Enter the package of your JUnit test
  10. Select the class you want to test
  11. Select a method to test
  12. Enter test successful in success message
  13. Enter 1000 in success code
  14. Enter test failed in failure message
  15. Enter 0001 in failure code
  16. Select the Thread Group
  17. Right click Add → Listener → View Results Tree
Couple of Things
1. JUnit test class should have a default constructor
2. In the Test plan add the jar to the class path



3. Check the JUnit 4 annotations


4. How to create a jar file for the projectmvn -DskipTests test-compile jar:test-jar install

Hope this helps :)








How to generate a jar using Maven


mvn -DskipTests test-compile jar:test-jar install

How to list the entire documents in Robo Mongo UI with pagination

How to list the entire documents in Robo Mongo UI with pagination

By default the pagination is 50 records










To Display the entire documents, here it is 170 records




Hope this helps :)

Inserting multiple documents from Robo Mongo

db.getCollection('foo').insertMany([{},{},{}])


Running Junit Test in Play 1.4

Create a JUNIT Test class

package utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.JsonElement;

import controllers.KPIDashboard;
import org.junit.Assert;
import play.libs.WS.HttpResponse;
import play.test.UnitTest;

public class PlayRequestBodyTester extends UnitTest{

    Dashboard dashboard = new Dashboard();
   

    @Test
    public void testValidRequestBody () {

    List wellUidList = new ArrayList<>();
    String requestBody =    "[{" + "wellUidList" + ":" + "[" + "4225534251" + ","
    +  "4225534256" + "]}]";
    wellUidList = dashboard.extractWellListFromRequestBody(requestBody);
    Assert.assertEquals(wellUidList, getActualWellUidList());
    }
   
    @Test
    public void testNullRequestBody () {

    List wellUidList = new ArrayList<>();
    String requestBody = null;
    wellUidList = dashboard.extractWellListFromRequestBody(requestBody);
    Assert.assertEquals(wellUidList, null);
    }
   
    private List getActualWellUidList () {
    List wellUidList = new ArrayList<>();
    wellUidList.add("4225534251");
    wellUidList.add("4225534256");
   
    return wellUidList;
    }
   
}


// Method to Test
    public static List extractWellListFromRequestBody (String requestBodyString) {
    List wellUidList = new ArrayList<>();
   
    if (requestBodyString != null && !"".equals(requestBodyString)) {
    System.out.println(requestBodyString);
    String [] wellArray = requestBodyString.substring(requestBodyString.lastIndexOf(":") + 1).replace("[", "").replaceAll("\"","" ).
    replaceAll("]", "").replaceAll("}", "").split(",");
    wellUidList= new ArrayList(Arrays.asList(wellArray));
    }
   
    return wellUidList;
    }

In the command prompt

run > play test

Once the application is loaded, go to the browser and 

http://localhost:9005/@tests

select the test class and hit "Start"






java.lang.UnsupportedClassVersionError: com/typesafe/config/ConfigException : Unsupported major.minor version 52.0

java.lang.UnsupportedClassVersionError: com/typesafe/config/ConfigException : Unsupported major.minor version 52.0

Java 8 has major version 52, which means if we run javac command from Java 8 installation, it will by default generate a class with major version 52. However, if we run class file in Java7, we will get "Unsupported major.minor version 52.0".
Solution :
There was a mis configuration in %JAVA_HOME%
  • java -version java version "1.8.0_44"
  • @echo %JAVA_HOME% C:\Program Files\Java\jdk1.7.0_75
To set the path temporary
  • set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_44
  • @echo %JAVA_HOME% C:\Program Files\Java\jdk1.8.0_44

How to increase code font size in IntelliJ?

File -> Settings -> Editor-> General -> (checked) Change font size (Zoom)


How to delete binded port from cmd in Windows?

How to delete binded port from cmd in Windows ?


To kill process on windows run below command to find port and pid
netstat -ano
to kill a process
taskkill /F /PID 1448

Failure to find com.microsoft.sqlserver:sqljdbc4:jar:4.0 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

Failure to find com.microsoft.sqlserver:sqljdbc4:jar:4.0 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

The issue is that Maven can't find this artifact in any of the configured maven repositories.
Unfortunately Microsoft doesn't make this artifact available via any maven repository. You need to download the jar from the Microsoft website, and then manually install it into your local maven repository.
You can do this with the following maven command:
mvn install:install-file -Dfile=sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar
Then next time you run maven on your POM it will find the artifact.

How to run Play framework 2.0 in Intellij

How to run Play framework 2.0 in Intellij

1. Play frameworks make use of build tool called sbt
2. First download the sbt plugin to Intellij
3. Go to File > Settings > Plugins > Install JetBrains plugins
4. Search and install


5. It will prompt to re-start Intellij
6. Once re-started, it will display a pop up to import the projects using sbt



7. In the Intellij, Go to View -- Tool Windows -- SBT, click on SBT


8. SBT will appear on the right side bar, click on that , the menu will pull out. Then right click on the project and select the option "Refresh SBT project"


You are all set.

Hope this helps :)



Keyboard shortcut synchronization with Eclipse and IDEA?

Keyboard shortcut synchronization with Eclipse and IDEA?

To get Eclipse Shortcuts, go to "Settings" and type "keymap". Then select Eclipse on the list.

How to remove before character or word in Notepad ++

How to remove before character or word in Notepad ++


i need to remove everything before the text "Insert" from a csv file given below


Use find and replace in notepad++
find: .+(\Insert) replace:  Insert



Output



Hope this helps :)

Converting a jar file to .exe

Converting a jar file to .exe

I have used Launch4j . It runs on both windows and linux

1. Download and install the application
2. Launch Launch4j 
3. In the Basic tab, Provide the full path of the output file, which obviously will be a .exe file in the         Outputfile textbox also browse the jar file you want to convert



4. In the Header tab select "Console" option


5. If you are using JDK, Go to JRE Tab and put in Min and Max versions



6. If you have certain files to be specified while running the jar file, you can add them as env. variables


7. You also can provide version information on the "Version" tab.

8. Now build the wrapper, using the settings icon on the top


Hope this helps :)
























 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days