Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm learning Mockito and Unit Testing in general. I want to learn how to unit test better by using Argument Captor. I'm using Spring jdbc to handle my SQL statement. I have a method that inserts a item into my DB.
public void update(Item item) {
   String sql = "SET NAME = ? where ID = ? ";
   jdbcTemplate.update(new PreparedStatementCreator() {
     public PreparedStatement createPreparedStatement(Connection connection) {
       final PreparedStatement ps = connection.prepareStatement(sql);
       ps.setString(1, item.getName());
       ps.setString(1, item.getId());
       return ps;

Open in new window

Below is the test that I'm trying to improve with ArgumentCaptor. This test will work because it is ensuring that insert is called with any PreparedStatementCreator.
      public void testUpdate() {
        Item item= new Item("testID","testName");
        verify(mockJdbc, times(1)).update(any(PreparedStatementCreator.class);

Open in new window

Below is the test with ArgumentCaptor.
      public void testUpdate() {
        Item item= new Item("testID","testName");
        ArgumentCaptor<PreparedStatementCreator> pscArgcaptor = ArgumentCaptor.forClass(PreparedStatementCreator.class);
        verify(mockJdbc, times(1)).update(captor.capture());
        assertEquals(pscArgcaptor , ?);

Open in new window

I can successful capture the PreparedStatementCreator call when I call update. I dont know how to get inside this object to verify my parameters in the prepared statement such as ps.setString(1, item.getId() and ps.setString(1, item.getName() to ensure that the prepared statement is the correct one.
The 14th Annual Expert Award Winners
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!


I tried to create a Certificate Signing Request using keytool: keytool -certreq -alias node01 -keystore node01.jks -file node01.csr -keyalg rsa -ext,ip: and got a keytool error: java.lang.Exception: Alias <node01> does not exist (attached Alias-Node01-Exception.png)
Do you have any idea how I can resolve the error.

I'm using Spring JDBC Template & @Transactional Annotation for all of my DB operations.

All the DB Update operation take more time and I see the row lock contention event occurring in the DB.

My application is used by 200 users approximately, the DB operations include updating the same table at a time but not the same row at a time.

Please see my code below.

public class EmployeeController{

    EmpService empService;

    @RequestMapping(value = "/startJob/{empID}", method = RequestMethod.GET)
    public ResponseEntity<String> getEmpDetails(@PathVariable(value = "empID") int empID) throws AOSException {
        // some logic
                String empDet = empService.getEmpDetails(empID);
        //some logic

public class EmpServiceImpl implements EmpService{

    EmpDAO empDAO;

    public String getEmpDetails(int empID){
        empDAO.copyEmpProfile(empID); // Oracle DB Stored Procedure call which has inserts.
        empDAO.operationB(empID); // Update Operations
        empDAO.operationC(empID); // Finally updates the status of employee.
        // Its taking long time for the third update statement and also all the other updates statements across the application are taking long time.


public class EmpDAOImpl implements EmpDAO{

    JdbcTemplate jdbcTemplate;

    public void copyEmpProfile(int empID){
I am having an issue with my Ansilbe script running  and have no idea what this error means , can some one send  me in the right direction ?

task path: /home/ec2-user/Projects/ocp-automation/RHEL-preconfig-playbook.yml:43
The full traceback is:
Traceback (most recent call last):
 File "/usr/lib/python2.7/site-packages/ansible/executor/", line 130, in run
   res = self._execute()
 File "/usr/lib/python2.7/site-packages/ansible/executor/", line 528, in _execute
   result =
 File "/usr/lib/python2.7/site-packages/ansible/plugins/action/", line 23, in run
   wrap_async = self._task.async_val and not self._connection.has_native_async
AttributeError: 'Task' object has no attribute 'async_val'

fatal: []: FAILED! => {}
I have been working on this for several days.  Not sure what the problem is.  I'm calling a Java web service from C#.  At first I tried to use WCF but I could not get that working.  I get kept getting a 400 bad request error.   I have successfully sent a request through SOAP UI.  

The request:
1) Has a payload with an attachment
2) An in going certificate
3) An outgoing certificate
4) SOAP 1.2

I decided to not use WCF and just try to do it manually.  Basically try to simulate what I did in SOAP UI.  

Here is my code:
string soap = "<?xml version='1.0' encoding='utf-8'?> <soap:Envelope xmlns:xsi='' xmlns:soap='' xmlns:xsd='' xmlns:int=''>" +
               "<soap:Header/> " +
                "<soap:Body> " +
                "	<int:xxxxxSubmission> " +
                "	xxxxxxxxxxxx " +
                "	</int:xxxxxSubmission> " +
                "</soap:Body> " +
                "</soap:Envelope> ";

            X509Certificate2 cert = new X509Certificate2(@"C:\Test\xxxxxx.pfx", @"xxxxx");
            X509Certificate2 cert2 = new X509Certificate2(@"C:\Test\xxx.cer", @"xxxxx");

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://xxxxx/TestService");

            req.ContentType = "application/soap+xml;charset=\"utf-8\"";
            req.Accept = "application/soap+xml";
            req.Method = "POST";

Open in new window

Hi All,

This is my frist python script working on... I would like to list the servers or cluster from websphere. The script contents are below...
run by cmd - wsadmin.bat -lang jython -F
Error -
WASX7209I: Connected to process "dmgr" on node dmgrNode using SOAP connector;  The type of process is: DeploymentManager
WASX7017E: Exception received while running file ""; exception information: exception from Jython:
Traceback (most recent call last):
  File "<string>", line 13, in <module>
ValueError: call stack is not deep enough

Content of the script - this example got from - C:\IBM\WebSphere\AppServer\scriptLibraries\servers\V70

# Set global constants
import sys
import java
import AdminUtilities

# Setting up Global Variable within this script
bundleName = ""
resourceBundle = AdminUtilities.getResourceBundle(bundleName)

# Retrieve scripting objects from local name space
AdminConfig = sys._getframe(1).f_locals['AdminConfig']
AdminApp = sys._getframe(1).f_locals['AdminApp']
AdminControl = sys._getframe(1).f_locals['AdminControl']
AdminTask = sys._getframe(1).f_locals['AdminTask']
Help = sys._getframe(1).f_locals['Help']    

## Example 1 List available servers with given server type and node ##
def …

I have a visual basic COM DLL & want to use this COM DLL from a java/JSP page. Basically I want to use some of the DLL method calls from JSP page. Can someone help me, give me some tips how to call COM dll from JSP Page?

Thank you!
public enum WhoisRIR {

    private String url;

    WhoisRIR(String url) {
        this.url = url;

    public String url() {
        return url;
public class Test {

    public static void main(String[] args) {




Open in new window

going through above code from below link

i was not clear how i got output as below

is enum like a class?
how enum different from java class?

when we use enum

not clear on below as well
Enum + Method + Some logic
public enum Operation {

    double calculate(double x, double y) {
        switch (this) {
            case PLUS:
                return x + y;
            case MINUS:
                return x - y;
            case TIMES:
                return x * y;
            case DIVIDE:
                return x / y;
                throw new AssertionError("Unknown operations " + this);

public class Test {

    public static void main(String[] args) {

        double result = Operation.PLUS.calculate(1, 2);
        System.out.println(result); //3.0


4. How to use Enum
4.1 To loop a Enum object.

public class Test {

    public static void main(String[] args) {

        for (UserStatus status : UserStatus.values()) {




Open in new window

please advise
Are there any research jobs in java. or companies that work quite in depth with java. how does one detect such companies...generally i have seen many companies will just be writing simple java code and much less using the deeper concepts like multithreading and other things in java. what kind of products will be using deeper concepts.

My code doesn't seem to send the post/get on my android app. I don't get anything from both ends which one is my server and also on my phone there is no respond sent but the studio just disconect from my phone its says application has terminated but my application is running but its sort of freeze. Here is my code.

try {
            final TextView outputView = (TextView) findViewById(;
            URL url = new URL("http://www.myurlhere/myfile.php");

            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");

             //Map<String, List<String>> headerFields = connection.getHeaderFields();
             //List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

            String urlParameters = "user=Admin&code=123";


            DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());


            int responseCode = connection.getResponseCode();
            final StringBuilder output = new StringBuilder("Request URL " + url);

Open in new window

Get expert help—faster!
LVL 12
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Before Spring Boot version 2.0 and Spring 5.0 we used the following code and it works perfectly fine without any issues.

public TomcatEmbeddedServletContainerFactory
tomcatEmbeddedServletContainerFactory() {
return new TomcatEmbeddedServletContainerFactory(){
    protected void customizeConnector(Connector connector) {
We have upgraded to Spring boot version 2.0 and Spring 5.0

Now after upgrading to Spring boot 2.0 and Spring 5.0 we no longer find the corresponding classes.

Can somebody help me with the equivalent package or newer maven pom.xml information to fix it ?

I'm getting a 400 Bad Request Error after calling a Java web service through C#.  I'm using Visual Studio 2015.  I got the WSDL file from the client and I added the file as a service reference in my solution.

Here is my app.config settings:
      <source name="System.ServiceModel.MessageLogging">
          <add name="messages"
          initializeData="c:\logs\messages.xml" />

          <binding name="CoreSoapPortBinding">
            <security mode="Transport">  
              <transport clientCredentialType="Certificate"/>  
        <endpoint address="https://xxxxxxxxx/ESARWS/CORETransactionService"
            binding="wsHttpBinding" bindingConfiguration="CoreSoapPortBinding"
            contract="ESAR.CORETransaction" name="CoreSoapPort" behaviorConfiguration="endpointCredentialBehavior" />

Open in new window

 * Add your code in the space below the comment line that says:
 * "*** Add your code BELOW this line (do not change ANYTHING above this line"
 * Do not change ANYTHING in the main method give below.
 * Write a good javadoc comment for EVERY method that you write.  Include one
 * or two sentences that give a good overview of what the method does, plus
 * the @param and @return directives (when appropriate).
 * The output your program should be exactly the same output as shown in the
 * sample output, including the same spacing, same placement of commas and
 * periods, upper and lowercase, etc.
 * Use good, descriptive variable names where appropriate.
 * Your code will be run against the main method as shown below, and also
 * against a different main method that will test your code more completely.
 * You should therefore test your code as fully as possible.
 * You do not need to define "public static final" values for the constants
 * (not required, but you can practice defining those if you wish).
public class ManyMethods {

     * Students should write method definitions for the all of the
     * methods called in this main method.  The code in the main method
     * should be left EXACTLY as it is.
     * @param args the command line arguments (not used in this program)
    public static void main(String[] args) {
        // The add method takes in two integers and returns …
I am working on a signature app that needs to save a copy of the signature as an image on the server. I am using and visual studio. The javascript I am using will give me a dataurl, but I need to be able to save this as an image on the server. I want to capture the current date and time of the signature as the filename, and be able to save a record of this filename to a column of one of my SQLtables so that I can associate the image with the customer in question. What is the best way to accomplish this? I am still somewhat new to javascript so a step-by-step or an example would be very helpful. If I get the dataurl to a serverside control then I do know how to save it, but because it is javascript/ client side I am stuck. Below is part of the script I am using which shows where I have gotten so far in getting the dataurl:

<script type="text/javascript">
$(document).ready(function() {
    var signaturePad = new SignaturePad(document.getElementById('signature-pad'), {
        backgroundColor: 'rgba(255, 255, 255, 0)',
        penColor: 'rgb(0, 0, 0)'
    var saveButton = document.getElementById('save');
    var cancelButton = document.getElementById('clear');

    saveButton.addEventListener('click', function (event) {
        var dataurl = signaturePad.toDataURL('image/png');

        // Save image to server or pass dataurl to server-side control.

    cancelButton.addEventListener('click', function (event) {
I have A xml File Where I have to Search <correspondenceTo>(.*?)</correspondenceTo>,if This tag is There Then we have to find in bettween <email> tag and cheak <Email> have in this format or not,<email>:&#x000A0;<email>,if not throw error

public void checkEntityTag(XMLContext xmlContext)throws Exception

                       System.out.println("journal name is"+CheckContent1.getFilePath());
                       File file=new File(CheckContent1.getFilePath());
                       BufferedReader b=new BufferedReader(new FileReader(file));
                       String readLine = "";
                        System.out.println("Testing checkEntityTag ");
                          Pattern  pat= Pattern.compile("<correspondenceTo>(.*?)</correspondenceTo>",Pattern.DOTALL);
                         while ((readLine = b.readLine()) != null) {
                                Matcher m=pat.matcher(readLine);
                	System.out.println(" Non Breakable Entity is missing in between Word \"+\"\\\"email\\\"\"+ \"and tag\" +\"\\\"&lt;email&gt;\\");

Open in new window

I'm using C# to call a Java Web Service.  I'm using Visual Studio 2015 The company gave me wsdl file and I generated the proxy class for wse 3.  I don't know WCF so I did it in wse 3

Here is my  app.config file

<?xml version="1.0" encoding="utf-8" ?>
		<section name="microsoft.web.services3" type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration, Microsoft.Web.Services3, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
				<add valueType="">
					<sessionKeyAlgorithm name="AES128" />
					<keyAlgorithm name="RSAOAEP" />
			<x509 storeLocation="CurrentUser" />
				<add type="Microsoft.Web.Services3.Security.Tokens.EncryptedKeyTokenManager, Microsoft.Web.Services3, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="" localName="EncryptedKey">
					<keyAlgorithm name="SHA2" />
			<trace enabled="true" input="InputTrace.webinfo" output="OutputTrace.webinfo" />
			<detailedErrors enabled="true" />
		<policy fileName="wse3policyCache.config" />
			<mtom clientMode="On" serverMode="always" />

Open in new window

Create an EmployeeException class whose constructor receives a String that consists of an Employee’s ID and pay rate.  Create an Employee class with two fields, IDNum and hourlyWage.  The Employee constructor requires values for both fields.  Upon construction, throw an EmployeeEception if the hourlyWage is less than 6.00 or over 50.00.  Write a test program (containing main method) that establishes at least three employees with hourlyWages that are above, below, and within the allowed range.
Tomcat 6 TLS1.2 enabled but still using SSL2 when opening an HTTP connection

Greetings, newbie here, so I might need help formatting the question properly.

I have a application running under Tomcat 6 that needs to run TLSv1.2.
I have install the JAVA runtime edition 6.0.181 which supports TLSv1.2.
I have configured the server.xml file to use TLSv1.2 with connections to clients and wireshark shows TLSv1.2 connections to the client when they are loading pages. But one of the pages makes an API call by opening a HttpURLConnection which also needs to use TLSv1.2 and I am unable to make that work. Wireshark shows that outgoing API call as SSLv2 and the Tomcat log show an "Connection reset" error.

This is the server.xml connector that comes so close.

                                port=”443” maxThreads=”200”
                                scheme=”https” secure=”true” SSLEnabled=”true”
                                SSLVerifyClient=”optional” sslEnabledProtocols=”TLSv1.2”/>

Here is the httpconnection code that needs to use tlsv1.2 to work:

String url = " https://www.tlsv12testsite/ ";  

            String agent = "Mozilla/4.0";
            String type = "application/x-www-form-urlencoded";
Any help would be greatly appreciated.  I'm attempting to compile sample code provided by Chase Paymentech.

The command that I'm running is "javac -classpath /home/danp/JPMC_MSDK_1.0.0/src".  I receive a bunch of errors saying that a bunch of packages don't exist.

The missing package messages include "error: org.apache.log4j does not exist".  I do have log4j, but it's located elsewhere on my server (not in org.apache).  

How can I point the compiler to  use log4j in the directory where it's already residing?

Free Tool: Subnet Calculator
LVL 12
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

I'm calculating values (based on input from one JSP) in a method in my Controller class and trying to pass it to another different JSP page using ModelAndView but I'm getting a weird `NumberFormatException` that I think refers to the value at line 249 from error below, ` 249:    <c:out value="${housepricesList.housePrice}"/>`:
    java.lang.NumberFormatException: For input string: "housePrice"

Open in new window

as well as another exception:
    2018-03-19 12:39:14.439 ERROR 2452 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [An exception occurred processing JSP page /houseprice.jsp at line 249

    248: <c:forEach items="${housepricesList}" var="HousePrice">     
    249:    <c:out value="${housepricesList.housePrice}"/>
    250:    <c:out value="${housepricesList.number_of_houses}"/>
    251: </c:forEach>

Open in new window

I'm getting a latitude and longitude from one JSP page, passing it to a method in my Controller where I use the lat & long values to query a database to return house prices within a 1km radius of initial latitude and longitude. I want to pass this returned information (`housePrice` and `number_of_houses`) to another JSP page. However the page won't load and the errors above are displayed in the console.

Controller Class
    	@RequestMapping(value = "/parseHousePrice", method = RequestMethod.POST)

Open in new window

I ran across some python code that allows continuous, live plotting of twitter stream data and sentiment rating. When the author of the code demonstrated it on Youtube, he was able to plot the twitter in a graph, and the graph updated  with each tweet. However, when I run the same code, I get one graph for each tweet and the plot points do not form a continuous line--instead the output consists of one graph, one plot point for each tweet. I would like to  get the graph to show the plotted point for all tweets in one chart in a continuous line.

BTW I am not the  only person who ran into this same problem with the code.  FYI I am currently running python 2.7,  in a Spyder 3.2.8 development environment on Mac.  I have attached the code (without access key information) and it has not been altered from the author's version. Any assistance would be greatly appreciated.

I had this question after viewing mapAB Challlenge.

after execution of the above code i am getting the following error
java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.
Writing a small GUI programme, and coming across a Warning (which I have suppressed / got rid of but ) which I don't understand :

warning: [path] bad path element "C:\EE_Q_CODE\packg": no such file or directory

I'm not referencing anything requiring resources in that non-existent folder, neither are there any jars or classes that are missing. So where is the idea coming from that this folder is required? Never seen such a phenomenon before.

As I say, I have got rid of the warning, (presently by adding an empty dir "packg" into the directory structure), but I'd very much like to know where the requirement for this is coming from. Any ideas please?
I need to read any type of file
encode it using huffman
decode it using huffman
MD5  Sum should match after decoding

only condition is the encoded file should have less size than original file
can anyone help me with that it can be done in java or C++
how to convert ArrayList Object in to byte[] ?






Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.