MyThinkPond

On Java, Python, Groovy, Grails, Spring, Node.js, Linux, Arduino, ARM, Embedded Devices & Web

Archive for the ‘Spring’ Category

Spring LDAP Overview | Baeldung

Posted by Venkatt Guhesan on March 13, 2017

Learn how to use the Spring LDAP APIs to authenticate and search for users, as well as to create and modify users in the directory server.

Source: Spring LDAP Overview | Baeldung

Posted in Spring, Spring Framework | Tagged: , , , , , , | Leave a Comment »

Developing email applications on Windows, targeted for Linux environment – email, mailx, sendmail

Posted by Venkatt Guhesan on December 11, 2016

linux_centos_logoIf you’re developing on a Windows platform for an application targeted for Linux or Unix that deals with email, then this article will be useful.

Let us begin by  understand the problem.

Problem

If you are a Java/Spring developer, (developing in Java is platform independent – runs on any platform where a JVM is available) then you have two options in front of you for sending emails from a Java application:

Option #1: JavaMail API

Option #2: Linux sendmail or mailx invoked via Runtime.getRuntime().exec(invoke – linux – mail – command) [example here]

If you are a PHP or Ruby or Bash or Python developer, you can do the same using a native library available within the language or invoke a native Linux execute-command to invoke either sendmail or mailx.

What happens if you are developing a hybrid library that needs to send email both from Java and Python. Then most likely you want to leverage a common library accessible to all the various libraries. In this case, you’re going to depend on either sendmail or mailx.   Now let us throw in a additional problem into this mix. Suppose you are developing on a Windows platform but the end application is targeted to run on Linux. This now creates a new additional problem. Sendmail or Mailx do not exist for Windows. Well, this article provides a way to develop on Windows by invoking execute mailx calls from your native code to the underlying emulation of Linux on Windows.

Now that we have established the problem, let us walk through a solution.

Please note that this is not the only solution but a potential solution. If you know of other mechanisms, feel free to send me a link and I’ll add them in.

Solution

Step-1: Make sure that you have Cygwin installed (with email tool selected additionally) on your Windows computer.

# Download  setup-x86_64.exe from https://cygwin.com/setup-x86_64.exe
# and run it.

# When you run the setup, please additionally select "email" tool additionally. It is not added by default.

Once Cygwin is installed, most people traditionally use all the Cygwin tools from within a Cygwin Command-Prompt. The executables are located under “\bin\**” directory. Which means that if you run a “ls” in a DOS command-prompt, it will error saying “command not found”. There is a undocumented\not so known secret to emulating Linux commands natively in Windows. This is where your true Linux power comes in under native Windows.

Step-2: Add Cygwin\bin path natively to Windows PATH.

# In my computer, I have Cygwin installed at the following path: c:\cygwin64\

To add "c:\cygwin64\bin" the system path, perform these steps:

1. Start the System Control Panel applet (Start - Settings - Control Panel - System).
2. Select the Advanced tab.
3. Click the Environment Variables button.
4. Under System Variables, select Path, then click Edit.
5. Add c:\cygwin64\bin to the path.

Once Step-2 is completed. If you start a new DOS command-prompt and run a “ls” command, you should see the directory listing (same as a ‘dir’ command under Windows).

Step-3: The send email application uses “c:\cygwin64\etc\email\email.conf” for SMTP and other email properties.

# Edit c:\cygwin64\etc\email\email.conf and add your SMTP details (domain/server name, user-id, password)
# For this example, I have setup a *special* GMail Email account specially to test [Don't use your private GMail] so I will use the user-id and password for that Gmail account.

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = '587'
USE_TLS = 'true'
SMTP_AUTH = 'LOGIN'
SMTP_AUTH_USER = 'YOUR_TEST_GMAIL_ADDRESS@gmail.com'
SMTP_AUTH_PASS = 'YOUR_GMAIL_PASSWORD_GOES_HERE'
MY_NAME  = 'Venkatt Guhesan'
MY_EMAIL = 'foobar7634@gmail.com'

Step-4: Let’s test this under a DOS command-prompt.

# Open a DOS Command-Prompt and run the following:

echo "Test from Cygwin in Windows under DOS command-prompt" | email -s "Testing Email from Windows DOS" recipient_email_address@gmail.com 

# Within minutes, you should see an email in the Gmail inbox as expected.

# If you are not seeing it, then you can use the example below where you can pass in the SMTP arguments for validation. Maybe you typed in the password for the Gmail account incorrectly or you entered one of the parameters incorrectly in the c:\cygwin64\etc\email\email.conf file.

############### HERE IS AN EXAMPLE WITH SMTP PARAMETERS PASSED IN AS ARGUMENTS #######################
echo "Test from Cygwin in Windows under DOS command-prompt" | email -s "Tetsing Email" recipient_email_address@gmail.com -r smtp.gmail.com -p 587 -m login -u YOUR_TEST_GMAIL_ADDRESS@gmail.com -i YOUR_GMAIL_PASSWORD_GOES_HERE -tls
######################################################################################################

ss1

Once you have confirmed a successful email then the next step is to create a mailx application.

Step-5: Create a mailx.exe (mailx) within Cygwin’s bin directory.

For emulating mailx from Cygwin’s email.exe, you’re in luck. The format for mailx is identical to the email.exe’s arguments. All you are missing is mailx.exe. So simply copy email.exe under Cygwin’s bin directory to mailx.exe under the same Cygwin’s bin directory. And you’re all set!

# simply copy email.exe under Cygwin's bin directory to mailx.exe under the same Cygwin's bin directory

cd c:\cygwin64\bin
cp email.exe mailx.exe

# Now just like you running email (without the .exe suffix) you can run mailx (without the .exe suffix)

Step-6: Test sending an email using mailx


echo "Test from Cygwin-mailx in Windows under DOS command-prompt" | mailx -s "Testing Email from Windows DOS" recipient_email_address@gmail.com 

ss2

As a last step, now within your Java application, test Runtime.getRuntime().exec(“mailx command”);

Runtime.getRuntime().exec("echo 'Test from Cygwin-mailx in Windows under DOS command-prompt' | mailx -s 'Testing Email from Windows DOS' recipient_email_address@gmail.com");

Now your Java application as well as any Python, Bash, Linux shell applications and/or scripts are now leveraging the common “mailx” and your development is now consistently the same using one common mailx library.

Cheers!

Today’s inspirational quote:
theodore-roosevelt
  • We must all either wear out or rust out, every one of us. My choice is to wear out.
– Theodore Roosevelt, an American statesman, author, explorer, soldier, naturalist, and reformer who served as the 26th President of the United States from 1901 to 1909.

Posted in Bash, CentOS 6.X, CentOS7, Grails, Groovy, Java, Linux, Spring, Windows | Tagged: , , , , , , | Leave a Comment »

Grails No profile found for name [web] illegalstateexception

Posted by Venkatt Guhesan on November 29, 2016

GrailsMost likely you’ve landed on this page because you’ve searched for the error in a search engine and it brought you here.

Symptom: When you run “grails” under an existing project that you previously had (either on a different PC or from a source-control like GIT or SVN and you’ve mistakenly included the “build” directory).

The associated error would have been one of the following:

Grails No profile found for name [web]

or

java.lang.IllegalStateException: No profile found for name [web].
at org.grails.cli.GrailsCli.initializeProfile(GrailsCli.groovy:507)
at org.grails.cli.GrailsCli.initializeApplication(GrailsCli.groovy:308)
at org.grails.cli.GrailsCli.execute(GrailsCli.groovy:271)
at org.grails.cli.GrailsCli.main(GrailsCli.groovy:162)
| Error Error occurred running Grails CLI: No profile found for name [web]

Either way, here’s how you can quickly resolve this issue and get back in business.

Solution:

Step-1: Remove “.grails” under your “home” directory.

rm -rf ~/.grails/

Step-2: Create a temporary *new* project

cd /temp/</pre>

grails create-app bookstore
# This will create a new scafolding and download the dependencies

Step-3: Remove the “build” directory under your *original* Grails project where you had the problem to begin with.

cd ~/my_original_grails_project/;
rm -rf ./build/
# Remove the old "build" directory

Step-4: Run Grails once again under your *original* Grails project

cd ~/my_original_grails_project/;
grails

You should see a whole bunch of dependencies being downloaded for this project like the following and you will end up with the Grails prompt:

Download https://repo.grails.org/grails/core/com/google/guava/guava/18.0/guava-18.0.pom
Download https://repo.grails.org/grails/core/com/google/guava/guava-parent/18.0/guava-parent-18.0.pom
Download https://repo.grails.org/grails/core/net/java/dev/jna/jna/4.1.0/jna-4.1.0.pom
Download https://repo.grails.org/grails/core/org/eclipse/jetty/jetty-util/9.2.18.v20160721/jetty-util-9.2.18.v20160721.pom
Download https://repo.grails.org/grails/core/org/eclipse/jetty/jetty-io/9.2.18.v20160721/jetty-io-9.2.18.v20160721.pom
Download https://repo.grails.org/grails/core/org/eclipse/jetty/websocket/websocket-common/9.2.18.v20160721/websocket-common-9.2.18.v20160721.pom
Download https://repo.grails.org/grails/core/org/eclipse/jetty/websocket/websocket-api/9.2.18.v20160721/websocket-api-9.2.18.v20160721.pom
Download https://repo.grails.org/grails/core/org/grails/grails-plugin-testing/3.1.10/grails-plugin-testing-3.1.10.jar
Download https://repo.grails.org/grails/core/org/grails/grails-test/3.1.10/grails-test-3.1.10.jar
Download https://repo.grails.org/grails/core/org/springframework/boot/spring-boot-starter-test/1.3.7.RELEASE/spring-boot-starter-test-1.3.7.RELEASE.jar
Download https://repo.grails.org/grails/core/org/seleniumhq/selenium/selenium-support/2.47.1/selenium-support-2.47.1.jar
Download https://repo.grails.org/grails/core/org/seleniumhq/selenium/selenium-remote-driver/2.47.1/selenium-remote-driver-2.47.1.jar
Download https://repo.grails.org/grails/core/org/eclipse/jetty/websocket/websocket-client/9.2.18.v20160721/websocket-client-9.2.18.v20160721.jar
Download https://repo.grails.org/grails/core/org/seleniumhq/selenium/selenium-api/2.47.1/selenium-api-2.47.1.jar
Download https://repo.grails.org/grails/core/com/google/guava/guava/18.0/guava-18.0.jar
Download https://repo.grails.org/grails/core/net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar
Download https://repo.grails.org/grails/core/org/eclipse/jetty/jetty-util/9.2.18.v20160721/jetty-util-9.2.18.v20160721.jar
Download https://repo.grails.org/grails/core/org/eclipse/jetty/jetty-io/9.2.18.v20160721/jetty-io-9.2.18.v20160721.jar
Download https://repo.grails.org/grails/core/org/eclipse/jetty/websocket/websocket-common/9.2.18.v20160721/websocket-common-9.2.18.v20160721.jar
Download https://repo.grails.org/grails/core/org/eclipse/jetty/websocket/websocket-api/9.2.18.v20160721/websocket-api-9.2.18.v20160721.jar
Download https://repo.grails.org/grails/core/org/grails/profiles/web/3.1.9/web-3.1.9.pom
Download https://repo.grails.org/grails/core/org/grails/profiles/base/3.1.9/base-3.1.9.pom
Download https://repo.grails.org/grails/core/org/grails/profiles/web/3.1.9/web-3.1.9.jar
Download https://repo.grails.org/grails/core/org/grails/profiles/base/3.1.9/base-3.1.9.jar
| Enter a command name to run. Use TAB for completion:
grails>

Now you’re all set and ready to go.

Cheers!

Today’s inspirational quote:
bust_of_marcusaurelius
  • When you need encouragement, think of the qualities the people around you have: this one’s energy, that one’s modesty, another’s generosity, and so on. Nothing is as encouraging as when virtues are visibly embodied in the people around us, when we’re practically showered with them. It’s good to keep this in mind.
  • You have power over your mind—not outside events. Realize this, and you will find strength.

Posted in Gradle, Grails, Java, Spring, Spring Framework | Tagged: , , , , , | Leave a Comment »

Gradle Spring Woes: Issues in creating single jar bundle with all dependency jars nested within

Posted by Venkatt Guhesan on November 3, 2016

springframeworkIf you’re implementing any projects with Spring and Gradle (for build), as your project grows you may run into this issue. Or you’ve landed on this page by searching on Google for “Unable to locate Spring NamespaceHandler for XML schema namespace” (your actual XML that it’s error-ing out may vary).

Either way, you’re in luck! Most likely, you’re using the fatjar gradle plugin to create a single JAR for executing as “java -jar one-big-bundle.jar”. The problem that happens is that if two or more dependent jar libraries contain the same file/artifact, then the last one wins the race in the fatjar bundle.

Let me illustrate this with an example:

Let’s say that your project depends on Spring-Context and Spring-Core. Within each jar, there maybe resources that have a common name such as META-INF/spring.schemas and/or META-INF/spring.handler (To learn more about the two individual files and their purpose in Spring, click on the links). When the fatjar combines the two JAR file, depending upon who goes last, the version of the above two files may belong to one or the other library. What should happen in reality is that it merges the two files contents. They maybe good for some files. But if you have a specific file in a format where you simply cannot concatenate the two files (such as a nested XML or JSON), simply combining the two files will not work. You may need to extend the Gradle plugin tasks to perform something selective and unique to your situation.

But if you ended up here after searching for “Unable to locate Spring NamespaceHandler for XML schema namespace” message, there is hope. You can simply, add the following to the fatJar Gradle plugin and problem is solved:

fatJarPrepareFiles {
  include 'META-INF/spring.handlers'
  include 'META-INF/spring.schemas'
}

A second option is to use a newer plugin called shadow. [User Guide]

...
apply plugin: 'com.github.johnrengelman.shadow'
...
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4'
    }
}
...
//For building a single jar with all dependencies run "gradlew shadowJar"
// Configure the shadow jar task
shadowJar {
    mergeServiceFiles()
}

jar {
    manifest {
        attributes 'Implementation-Title': 'application name',
                'Implementation-Version': version,
                'Main-Class': 'com.guhesan.fooapp.Application'
    }
}

Cheers!

Today’s Inspirational Quote:

…Bliss is not something to be got.
On the other hand you are always Bliss.
This desire [for Bliss] is born of the sense of incompleteness.
To whom is this sense of incompleteness? Enquire.
In deep sleep you were blissful.
Now you are not so.
What has interposed between that Bliss and this non-bliss?
It is the ego.
Seek its source and find you are Bliss.
Ramana Maharishi|2nd link (Spiritual Teacher & one of the great minds of this century)

-AUM

Posted in Gradle, Grails, Spring, Spring Framework | Tagged: , , , , , | Leave a Comment »

Tomcat 6+: Infamous “SEVERE: Error listenerStart” message – How-To debug this error?

Posted by Venkatt Guhesan on July 1, 2011

I’m sure if you have been developing with Java and Tomcat for sometime, you are likely to run into the infamous debug error.

SEVERE: Error listenerStart

You will most likely start Googling it trying to find out what the heck is going on. And in trying to see the extended logging on what that “listenerStart” error means. After some lucky searches, you will see links asking you to drop a “log4j.properties” file under ‘/WEB-INF/classes’ directory inside your WAR to help debug which one of the listeners is throwing this crazy error.

Well, this advise will most likely work for you if you are developing under an earlier version of Tomcat. If you are using versions 6.0 or above then continue to read on…

In Tomcat 6 or above, the default logger is the”java.util.logging” logger and not Log4J. So if you are trying to add a “log4j.properties” file – this will NOT work. The Java utils logger looks for a file called “logging.properties” as stated here:
http://tomcat.apache.org/tomcat-6.0-doc/logging.html

So to get to the debugging details create a “logging.properties” file under your”/WEB-INF/classes” folder of your WAR and you’re all set.

And now when you restart your Tomcat, you will see all of your debugging in it’s full glory!!!

Sample logging.properties file:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

and you will most likely see a “class-not-found” exception. 😉

Look at the bright side, you’re now one step closer to the solution.

Happy coding!

Posted in Grails, Groovy, GWT, Java, Spring, Spring Framework, Tomcat, web development | Tagged: , , , , , | 25 Comments »

Spring Framework Samples and Reference Implementations online in svn

Posted by Venkatt Guhesan on April 19, 2010

Sometimes it’s good to look at the svn repository for the reference sample that Spring Framework provides.

Here’s a quick link for that URL:

https://src.springframework.org/svn/spring-samples/

You can traverse through it via a HTTP(s) browser or you can download the latest samples via tools like TortiseSVN.

Here is a list of some of the projects samples that are available today:

spring-samples – Revision 431: /

* configuration-basic/
* jpetstore/
* mvc-ajax/
* mvc-basic/
* petcare/
* petclinic/
* petclinic-groovy/
* spring-travel/
* task-basic/
* templates/
* tutorials/

Hopefully this article will be beneficial for someone who is trying to get familiar with Spring Framework.

Cheers.

Posted in Java, Programming, Spring, Spring Framework | Tagged: , , | Leave a Comment »

Spring 3.0 – Application Context – three ways to get the context

Posted by Venkatt Guhesan on March 22, 2010

In searching Google for “Spring ApplicationContextAware“, you come across a lot of recommendations and I also see a lot of folks continuing to complain saying that their setApplicationContext method does not get invoked. So to help clarify, I’m blogging a few notes in hope that it helps clarify a few things.

Two Ways to Get Application Context:

Method #1:  In your class you implement ApplicationContextAware class like this:


public class MyClass implements ApplicationContextAware {

    static final long serialVersionUID = 02L;

    ApplicationContext applicationContext = null;

    public void doSomething(){
        if (applicationContext != null && applicationContext.containsBean("accessKeys")){
            MyBean beanA = (MyBean) applicationContext.getBean("mybean");
            //Do something with this AccessBean
        }

        return null;
    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        System.out.println("setting context");
        this.applicationContext = applicationContext;
    }

}

Method #2: If you are in a Java Servlet, you can do the following:


public class gzservlet extends HttpServlet {
    static final long serialVersionUID = 02L;

    ApplicationContext applicationContext = null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (applicationContext == null){
            System.out.println("setting context in get");
            applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        }
        if (applicationContext != null && applicationContext.containsBean("accessKeys")){
            AccessBean thisAccessBean = (AccessBean) applicationContext.getBean("accessKeys");
            req.setAttribute("keys", thisAccessBean.toString());
            System.out.println("setting keys");
        }

        req.getRequestDispatcher("/index2.jsp").include(req,resp);
    }

}

So the question one would ask is when to use what? And the answer is. Depends on how you are invoking Spring.

What works for Method #1: when you invoke Spring you are using the DispatcherServlet link this. Then Method #1 will resolve the implementation of ApplicationContextAware and call the setApplicationContext() method to set the context.

In web.xml.

<servlet>
	<servlet-name>dispatchservlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>dispatchservlet</servlet-name>
	<url-pattern>/*</url-pattern>
</servlet-mapping>

If you are not using the DispatcherServlet and you are initializing Spring using a Listener and you have your own Servlet that’s driving the Request\Response scope then use Method #2. Below is an example of how the web.xml will look like in this case.


<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
  <servlet-name>MyOwnServlet</servlet-name>
  <servlet-class>com.something.myservlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>MyOwnServlet</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

I hope this clarifies why sometimes even though you have implemented the ApplicationContextAware interface, your setter does not get invoked.

[09/12/2010] Here is a third way to get your context:

Create the following class with a static method to get your context:


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware{
 private static ApplicationContext ctx = null;
 public static ApplicationContext getApplicationContext() {
return ctx;
 }
 public void setApplicationContext(ApplicationContext ctx) throws BeansException {
this.ctx = ctx;
 }
}

and in your spring bean configuration xml file add the following:


<bean id="applicationContextProvider" class="ApplicationContextProvider"></bean>

And now in your classes, you can do the following:

ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();

That’s it!!!

Cheers.

If you find this article useful, consider signing up for my RSS feed or Email Newsletter. See links on the right side.

Posted in Programming, Spring | 31 Comments »