Java Web Applications web.xml Basic Fundamentals

0

Java Web Applications

      use a deployment descriptor file to determine how URLs map to servlets
      web.xml is the file is the deployment descriptor
      some URL’s require authentication
      resides in the WEB-INF folder
      describes the classes, resources and configuration of the application
      maps the URL of the request to the code that handles the request

    Example

    Below, the java class is mapped to the url’s here.

    <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
        <servlet>
            <servlet-name>comingsoon</servlet-name>
            <servlet-class>mysite.server.ComingSoonServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>comingsoon</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    </web-app>
    

    Example

    Below, the web.xml defines key value pairs

     <servlet>
            <servlet-name>redteam</servlet-name>
            <servlet-class>mysite.server.TeamServlet</servlet-class>
            <init-param>
                <param-name>teamColor</param-name>
                <param-value>red</param-value>
            </init-param>
            <init-param>
                <param-name>bgColor</param-name>
                <param-value>#CC0000</param-value>
            </init-param>
        </servlet>
    String teamColor = getServletConfig().getInitParameter("teamColor");
    

    JSP

    JSP’s are servlets also :). That define static content mixed with Java code.

    Filters

    A filter is a class that acts on a request like a servlet, but may allow the handling of the request to continue with other filters or servlets. A filter may perform an auxiliary task such as logging, performing specialized authentication checks, or annotating the request or response objects before calling the servlet.

    A filter implements javax.servlet.Filter, includes doFilter() method.

    Error Handlers

      <error-page>
            <error-code>500</error-code>
            <location>/errors/servererror.jsp</location>
        </error-page>
    

    ld: library not found for -l

    0

    To build as libary

    Right Click->Properties->Build->Setting-Build Artifact->Dropdown to choose Shared/Static library

    Difference between Shared / Static library

    Now to include this library, copy the library to the project you want it and put it in a libs folder at the same level as the src level. Note, I am assuming that you have a src folder.

    On thisĀ project Right Click->Properties->Build->Setting->Libraries->

    1. in the -l area add name of library without the prefix lib and without the suffix .so
    2. in the -L area add ../libs, remember its 2 dots since the current folder is src, not the root of the project šŸ™‚ YEAH, I tried ./libs for 1 hours before trying out ../libs

     

    Building our first C++ cuda library

    0

    So the first thing you do when you get CUDA ready is try your hands out on the sample code and NSight (the eclipse of CUDA). This goes smoothly, but as soon as you start writing cpp codeĀ for developing libraries, you can hit all kinds of issues. This post has fixes for those crazy issues that has no help on even StackOverflow.

    Reference

    #include "common.h"
    #include <cuda_runtime.h>
    #include <sys/time.h>
    #ifndef _TIMER_H
    #define _TIMER_H
    class Timer {
    public:
     enum class TIMER_FORMAT {
     MILLISECONDS, MICROSECONDS, NANOSECONDS, SECONDS
     };
    enum class PROCESSOR_CONFIG {
     HOST, DEVICE
     };
    __host__ Timer(PROCESSOR_CONFIG config);
     __host__ ~Timer();
     __host__ void StartTimer();
     __host__ void StopTimer();
     __host__ double GetElapsedTime(TIMER_FORMAT format);
    protected:
     cudaEvent_t m_eventStart;
     cudaEvent_t m_eventStop;
     PROCESSOR_CONFIG m_config;
     double m_startTimeInNS;
     double m_stopTimeInNS;
    };
    #endif // _TIMER_H
    
    Timer.cu
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    
    #include "Timer.cuh"
    
    Timer::Timer(PROCESSOR_CONFIG config) {
     if (config == Timer::PROCESSOR_CONFIG::DEVICE) {
     CHECK_API_FOR_ERROR(cudaEventCreate(&m_eventStart));
     CHECK_API_FOR_ERROR(cudaEventCreate(&m_eventStop));
     } else {
    #ifdef __COMPILE_FOR_WINDOWS__
     LARGE_INTEGER lpFrequency;
     if (QueryPerformanceFrequency(&lpFrequency) == 0) {
     printf("Could not query performance frequency on CPU");
     m_performanceFrequency = 0;
     }
     else
     m_performanceFrequency = lpFrequency.QuadPart;
    #endif
     m_startTimeInNS = 0;
     m_stopTimeInNS = 0;
     }
     m_config = config;
    }
    
    Timer::~Timer() {
    }
    
    void Timer::StartTimer() {
     if (m_config == Timer::PROCESSOR_CONFIG::DEVICE) {
     CHECK_API_FOR_ERROR(cudaEventRecord(m_eventStart));
     } else {
    timespec ts;
     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
     m_startTimeInNS = ts.tv_nsec;
    }
    }
    
    void Timer::StopTimer() {
     if (m_config == Timer::PROCESSOR_CONFIG::DEVICE) {
     CHECK_API_FOR_ERROR(cudaEventRecord(m_eventStop));
     CHECK_API_FOR_ERROR(cudaEventSynchronize(m_eventStop));
     } else {
    timespec ts;
     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
     m_stopTimeInNS = ts.tv_nsec;
    }
    }
    
    double Timer::GetElapsedTime(TIMER_FORMAT format) {
     double elapsedTimeInNanoseconds = 0;
    
     if (m_config == Timer::PROCESSOR_CONFIG::DEVICE) {
     float elapsedTimeInMilliseconds = 0;
     CHECK_API_FOR_ERROR(
     cudaEventElapsedTime(&elapsedTimeInMilliseconds, m_eventStart,
     m_eventStop));
     elapsedTimeInNanoseconds = elapsedTimeInMilliseconds * 1000.0 * 1000.0;
     } else
     elapsedTimeInNanoseconds = m_stopTimeInNS - m_startTimeInNS;
    
     switch (format) {
     case TIMER_FORMAT::MILLISECONDS:
     return elapsedTimeInNanoseconds / (1000 * 1000);
    
     case TIMER_FORMAT::MICROSECONDS:
     return (elapsedTimeInNanoseconds / 1000);
    
     case TIMER_FORMAT::NANOSECONDS:
     return (elapsedTimeInNanoseconds);
    
     case TIMER_FORMAT::SECONDS:
     return (elapsedTimeInNanoseconds * 1000 * 1000 * 1000);
    
     default:
     return 0;
     }
    }
    
    int main(int argc, char* argv[]) {
    
    }
    
    
    • Syntax Error :Ā For some reason I got a “Syntax Error” on the constructor and destructor lines of my CPP code. To fix this, rename your .cpp as .cu. And rename your .h as .cuh.
    • My enumsĀ PROCESSOR_CONFIG, would not resolve at Ā Timer::PROCESSOR_CONFIG::DEVICE. I had a similar issue to this. To fix this I had to compile using a C11 directive. I used this, to fix it. Refer to my answer (Siddharth).
    • Finally I had to add a main (I need to get rid of this expectation soon).

    Android Camera, does not return to onActivityResult and resets calling activity

    0

    What is surprising is that the documented way of making this shit work does not work.

    http://developer.android.com/guide/topics/media/camera.html

    Scroll to Image Capture Intent,

    // photoIDFile is type File
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoIDFile)); // set the image file name

    With this it just does not work. My Uri is correct, I have

    file:///data/data/com.samagra.operatorapp/files/photo1441253398999.jpg

    But this gets the camera to return.

    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoIDFile).toString()); // set the image file name

    Now the camera resets my activity and I loose my activity, it goes back SHAMELESSLY.

    I had to read through the Camera documentation on android.developer.com and read Building a Camera App section. This worked well.

    Dreaded Exception SEVERE: A message body writer for Java class, MIME media type application/json

    0

    Gone are the days when error messages made sense. Something as simple as Annotation Missing has been replaced by something silly as MIME media type application.

    The crazy exception below translates to having the following annotations in the ConsolidationSearchForUsersResponse class

    @XmlRootElement(name = "Response")
    @XmlAccessorType(XmlAccessType.FIELD)

    </code>

    Crazy Log shit

    INFO com.mcruiseon.atom.endpoint.EndPointConsolidation - SearchUsers,
    Aug 13, 2015 12:46:16 AM com.sun.jersey.spi.container.ContainerResponse write
    com.mcruiseon.atom.endpoint.response.ConsolidationSearchForUsersResponse, and Java type class com.mcruiseon.atom.endpoint.response.ConsolidationSearchForUsersResponse, and MIME media type application/json was not found
    Aug 13, 2015 12:46:16 AM com.sun.jersey.spi.container.ContainerResponse write
    SEVERE: The registered message body writers compatible with the MIME media type are:
    application/json ->
    com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$App
    com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$App
    com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$App
    com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$App
    com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$App
    */* ->
    com.sun.jersey.core.impl.provider.entity.FormProvider
    com.sun.jersey.core.impl.provider.entity.StringProvider
    com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
    com.sun.jersey.core.impl.provider.entity.FileProvider
    com.sun.jersey.core.impl.provider.entity.InputStreamProvider
    com.sun.jersey.core.impl.provider.entity.DataSourceProvider
    com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
    com.sun.jersey.core.impl.provider.entity.ReaderProvider
    com.sun.jersey.core.impl.provider.entity.DocumentProvider
    com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider
    com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
    com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
    com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$General
    com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$General
    com.sun.jersey.json.impl.provider.entity.JSONWithPaddingProvider
    com.sun.jersey.server.impl.template.ViewableMessageBodyWriter
    com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
    com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
    com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
    com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General
    com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy

    Aug 13, 2015 12:46:16 AM com.sun.jersey.spi.container.ContainerResponse logException
    SEVERE: Mapped exception to response: 500 (Internal Server Error)
    javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.mcruiseon.atom.endpoint.response.ConsolidationSearchForUsersResponse, and Java type class com.mcruiseon.atom.endpoint.response.ConsolidationSearchForUsersResponse, and MIME media type application/json was not found
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1448)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1360)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1350)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.mcruiseon.atom.endpoint.response.ConsolidationSearchForUsersResponse, and Java type class com.mcruiseon.atom.endpoint.response.ConsolidationSearchForUsersResponse, and MIME media type application/json was not found
    ... 28 more

    Aug 13, 2015 1:02:09 PM org.apache.catalina.core.StandardContext reload
    INFO: Reloading Context with name [/AtomEndPoint] has started
    Aug 13, 2015 1:02:09 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
    SEVERE: The web application [/AtomEndPoint] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
    Aug 13, 2015 1:02:09 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/AtomEndPoint] appears to have started a thread named [C3P0PooledConnectionPoolManager[identityToken->z8kfsx9b9t027hydr9jt|140323e]-AdminTaskTimer] but has failed to stop it. This is very likely to create a memory leak.
    Aug 13, 2015 1:02:09 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/AtomEndPoint] appears to have started a thread named [C3P0PooledConnectionPoolManager[identityToken->z8kfsx9b9t027hydr9jt|140323e]-HelperThread-#0] but has failed to stop it. This is very likely to create a memory leak.
    Aug 13, 2015 1:02:09 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/AtomEndPoint] appears to have started a thread named [C3P0PooledConnectionPoolManager[identityToken->z8kfsx9b9t027hydr9jt|140323e]-HelperThread-#1] but has failed to stop it. This is very likely to create a memory leak.
    Aug 13, 2015 1:02:09 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/AtomEndPoint] appears to have started a thread named [C3P0PooledConnectionPoolManager[identityToken->z8kfsx9b9t027hydr9jt|140323e]-HelperThread-#2] but has failed to stop it. This is very likely to create a memory leak.
    Aug 13, 2015 1:02:09 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/AtomEndPoint] appears to have started a thread named [Thread-5] but has failed to stop it. This is very likely to create a memory leak.

    Learning Rails (on ubuntu)

    0

    As a java developer, learning ruby can be a daunting task. But I seem to have lived through the pain and hopefully this blog will help those who want to learn Ruby.

    This blog will help you understand how to setup a development environment and the right places to look for to learn the language.

    So to setup the ruby environment, I first started with a the correct editor. Sublime is it. Dont consider others (for now atleast). I then installed ruby language and all its other libraries as needed. After that I started with my Ruby On Rails learning. Rails is nothing but a deployment environment for Ruby. Helps to get started with Ruby faster.

        http://www.codelearn.org/ : Is a good place to start learning. They have one thing missing after the first Lesson, you will get help here. What you will need from this link is

        gem install bundler
        bundle init

        Now here you will find that rails server will create a new folder. DAMN!! why the hell does it do this shit?. Dont wonder too much, its just stupid. You need to follow this link to fix it.

        When you create your application with rails new myApp, there should be a myApp/script directory and in there will be a script named rails, this is the rails that understands server and console. So, do this:
        $ rails new MyApp
        $ cd MyApp
        $ script/rails server
        To create and start up your application. The naming is a little confusing.

        This also did not work, OK, try this then.

        cd script
        ./server

        Now, you will need to run a command line “rails generate controller pages about help”. This too will not work since “rails” will run from the command instead you should run script/generate. Yeah!! Its that silly!!