Posts tagged java

Oracle Java Developer Conference

2

Mám v poslední době takovej nějakej dojem, že navštívené konference mi nějak nic nedávají. Otázka je, jestli stárnu, nebo jestli za to může fakt, že jsem se den před touto konferencí nepěkně picnul a modlil se, ať už to skončí. Pravda ovšem může být úplně jinde – recykluje se. No a protože slíbené slajdy z androidDevCampu pořád nejsou (a nemůžu tu komentovat co jsem chtěl), zkusím se zamyslet nad tím, co se mi děje.

Vzpomínám si, jak jsem se „zamlada“ těšil na Invex, asi tak moc, jak jsem tuto akci potom nenáviděl. Důvod se mi zdá prostý – internet a přebytek informací (Brave new world). Pokud se člověk o něco zajímá, určitě má dané téma nastudované ze všech stran a zná detaily. Proto mi svého času přišlo zbytečné chodit na výše zmíněnou výstavu. Stejný dojem bohužel začínám získávat i z různých konferencí. Pokud člověk nejede vyloženě získávat kontakty (případně se dobře najíst či flirtovat s hosteskama), bude to zabitý čas.

Oracle Java Developer Conference

Oracle Java Developer Conference

Posledních několik týdnů jsem se věnoval hlubšímu studiu Enterprise edition Javy (všechny ty servlety a podobné věci už potkávám pár let, ale injektáže a další věci mimo Spring jsem si ještě pořádně neošahal), tak jsem se těšil, že nabudu nové tipy a směrovky, na co se dále podívat… bohužel. Dopolední část programu bylo víceméně vzájemné plácání se přednášejících po ramenou, co že se povedlo, jak to bylo tenkrát, jak je to teď… zakončené povídáním Aleše Koběrského z Home Creditu, co že vlastně dělají a jak to u nich vypadá. Jasně, z velké části na akci byli studenti, kteří budou hledat job, ale stejně mi to nesedí. Navíc je otázka, jestli vůbec budou mít zájem (u oběda porovnávali nabídky různých firem, tam že dávají auto, tam jiné benefity…), jestli si nevysnili něco úplně jiného (pečené holuby zadarmo do huby).

Oracle Java Developer Conference

Oracle Java Developer Conference

Po obědě to začalo být zajímavé – Martin Marko (Web development for java web developers. Bad practices and solutions) rozjel show na téma jakýchsi vlastních dá se říci šablonovacích systému a přednášky o tom, že jako Javisti bychom neměli psát html kód a pokud ano, nepsat jej jak prasata. Chápu, souhlasím! Měl neuvěřitelný flow a těch 45 minut uteklo jak voda, dokázal bych tam sedět klidně až do večera – tohle mi něco dalo! Teď se však marně snažím najít nějaký jeho blog (blogspot mi hlásí 404), názvy které zmiňoval ani googlu nic neříkají (html5taglib, haiku), takže tu nemůžu dát linky. Ale aspoň jsem sehnal jeho mejl, tak uvidíme, jestli se s tím bude dát něco dělat, protože to bylo rozhodně nemálo zajímavé.

Další navštívenou přednáškou byla opakovaná What’s new in JavaEE 6 prezentovaná Alexis Moussine-Pouchkine, ale spíše jsem si během ní srovnával v hlavě Marcusova slova. Občas jsem ale procitl, abych zjistil, že se recyklují věci jako qualifiers (se kterými jsem shodou okolností neúspěšně zápasil minulý týden), že se ukazují onelinery oanotované asi deseti řádky a další šílenosti. Sečteno podtrženo – nula. A to jsem seděl na zemi, protože bylo plno.

Javistky nevypadají jako matfyzák

Javistky nevypadají jako matfyzák

OK, další v plánu mám „Vývoj a architektura java aplikace pro 10 mil. uživatelů“ prezentované Ladislavem Skokanem. Jednalo se o popis řešení online aplikace pro sčítání obyvatel. No opravdu se nezlobte, ale informace o tom, že to jede na web logicu, „tady jsme potom přidali ještě jeden server“, „čteme data z databáze, tak je vhodné cachovat“…k čemu tato prezentace byla? Možná k pláči. Takže se na mě, vážení pořadatelé, nezlobte, ale odcházím. Vypouštím Contexts and Dependency Injection i MDA platformy Paternoster (pokud je vůbec za tím MDA skryta Model Driven Architektura).

Na závěr ještě zamyšlení – proč jsou novinky prezentovány vývojářům, když ti v těžké většině nemohou mít na výběr použité technologie pražádný vliv? Jasně, pokud dělám vlastní projekt, rád si ozkouším mnoho věcí a novinek, ale pokud by se mělo jednat o nějaký long-term projekt – kdo by riskoval použití novinek z něčeho, co se mění dle měsíčních fází? Nehledě na to, že zadavatel si většinou vybere něco, co už je drahně let za horizontem a co dokáží jeho ajťáci spravovat? Slovy klasika: „srsly, wtf?“ Možná by byly do budoucna vhodnější nějaké detailně probrané case studies konkrétních implementací, případně workshopy, nebo reálné zkušenosti. Že by právě proto tolik frčely všechny ty hackathony a klasické konfery začínaly taky patřit do doby dinosaurů?

PS. Negativní vyznění nemá nic společného s tím, že jsem nedostal kabelku s letáky a reklamní flashdisk, ani fakt, že jsem se večer před konferou nepěkně sejmul.

Jak se dostat na zabezpečené služby státní správy?

0

Pod mírně bulvárním názvem tohoto blogpostu nehledejte žádný návod na hákování webů státních institucí. Pouze jsem se snažil vytvořit klienta (v Javě) pro komunikaci s webovými službami nalézajícími se na serveru, který je zajištěn certifikátem vydaným certifikační autoritou PostSignum a aby to nebylo tak jednoduché, tak uživatel je autentikován na základě osobního certifikátu.

Každý slušný člověk začne nejprve googlením, kdy najde nejeden příklad navazování spojení pomocí https (řekněme HTTP over TLS), další googlení potom poodkryje další příklady, tentokrát jak použít klientský certifikát. Na tomto základě už je možné začít stavět, nejprve tedy metoda pro získání ssl socket factory, kterou použijeme pro kontrolu identity:

private SSLSocketFactory getFactory(File pKeyFile, String pKeyPassword) throws...{
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    InputStream keyInput = new FileInputStream(pKeyFile);

    keyStore.load(keyInput, pKeyPassword.toCharArray());
    keyInput.close();
    keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

    return context.getSocketFactory();
}

Tato factory se předá do vytvářeného zabezpečeného spojení, kdy je tímto způsobem poskytnut údaj pro autentikaci uživatele na straně serveru. Tedy metoda vracející toto spojení:

public HttpsURLConnection getConnection() throws ...{
    URL url = new URL("https://server:844/");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

    con.setSSLSocketFactory(getFactory(new File("cert_sign.p12"), "heslo"));

    return con;
}

Teď je možné se pomocí zavolání connect() připojit, ale protože nejsou v úložišti důvěryhodných certifikátů vložené certifikátu serveru, snaha o připojení skončí s výjimkou:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Nejprve jsem se snažil mezi důvěryhodné certifikáty importovat certifikát kořenové autority PostSignum pomocí nástroje keytool

sudo keytool -import -alias gwc.cpost.cz -keystore /etc/java-6-sun/security/cacerts -file root.pem

což však nevedlo nikam, potřeboval jsem konkrétní certifikáty konkrétního stroje a s tím mi pomohla utilitka InstallCert (zdrojový kód, takže je to důvěryhodné ;-)). Vytvořený soubor jssecacerts je vlastně původní cacerts s přidanými certifikáty požadovaného serveru, takže je možné jej nakopírovat na odpovídající místo, pomocí keytool -list se podívat, jestli je vše v pořádku a opět vyzkoušet spojení.

Spojuje se, ale to je tak celé, takže se teď zabývám následujícími odkazy:

MVC and Spring surf

17

One of things I missed in Spring Surf are Models and Controllers. I tried many ways to get them working, but still no useful solution. So I chose really simple way to do that – to define another dispatcher and to play with urlrewrite. In this post I’ll describe what I did and as a little bonus you’ll find a breathtaking example 🙂 – YUI based Ajax whisperer.

Let’s start with empty Spring Surf skeleton:

project --topLevelPackage cz.shmoula.controllers
surf install
perform eclipse

Now add dispatcher – in web.xml we have to define new servlet with name controller, loaded as second and with url-pattern /app (default dispatcher is mapped to /service), which is filtered by urlrewrite.

<servlet>
  <servlet-name>controller</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>controller</servlet-name>
  <url-pattern>/app/*</url-pattern>
</servlet-mapping>

In next step we’ll need web application config – Spring names them as -servlet.xml prefixed with servlet name. So let’s create controller-servlet.xml in WEB-INF (in STS New/Spring bean configuration file) and add some useful stuff there: for first we want to use annotations for our controllers, so let’s add there two beans – DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter.

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

Then we need to define where are our controllers lying, so let’s define base package.

<context:component-scan base-package="cz.shmoula.controllers.controller" use-default-filters="false">
  <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>

Last thing is to tell, where will be our views and which suffix they use.

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
</bean>

Okay, folks, that’s almost all! Now the interesting part: Writing the controller. Make a class in package we defined earlier. It should extend some AbstractController or another stuff, but it’s not necessary, we’ll simple it! 😉 Put a test method inside:

package cz.shmoula.controllers.controller;

@Controller
public class AutocompleteController{

  @RequestMapping(value = "/test")
  public String test(Model model){
    model.addAttribute("attribute", "Some sample string");
    return "test";
  }
}

That’s our controller. Now we need a view. Previously we defined parameters for view resolver and in controller we’re returning name of our model. Putted together result is: /WEB-INF/jsp/test.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test page backed by controller</title>
  </head>
  <body>
    <h1>Hi, what we have there?</h1>
    <p>${attribute}</p>
  </body>
</html>

Last thing to do is to define some rules for urlrewrite. We’ll try to forward all /app/ requests to our dispatcher and anything else to Default Spring Dispatcher. That’s done by these rules (urlrewrite.xml):

<rule>
  <from>/app/(.*)</from>
  <to>/app/$1</to>
</rule>
<rule>
  <from>/</from>
  <to>/service/</to>
</rule>

Done? So let’s test it! Run it up and open browser at http://localhost:8080/controllers/app/test. Does it work? I hope so!

Test page

Test page

That was the first part – worst one, now came pure fun – some functionality. We want to implement some buzzlike thingy as Autocompletion is – whisperer. To keep it simple our model layer will be just a Collection with Strings, so let’s modify our controller with constructor:

private Collection<String> termList = new HashSet<String>();
public AutocompleteController() {
    termList.add("Prague");
    termList.add("Paris");
    termList.add("Poznan");
}

Now we need controller code – something returning some results. So at /autocomplete will be routine, which waits for „query“parameter with part of String, which tries to find in termList and return:

@RequestMapping(value = "/autocomplete")
public void autocomplete(HttpServletRequest httpRequest, Model model) {
    String query = httpRequest.getParameter("query");
    String response = "";

    if (query != null) {
        for (Iterator<String> i = termList.iterator(); i.hasNext();) {
            String term = i.next();
            if (term.startsWith(query))
                response += "n" + term;
        }
    }
    model.addAttribute("response", response);

}

Now we have to render our model through something, so add view /WEB-INF/jsp/autocomplete.jsp:

${response }

And now to add all that into widget. Let’s extend calendar widget in /WEB-INF/webscripts/calendar – first add styles and YUI scripts into calendar.get.head.ftl:

<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.8.2r1/build/autocomplete/assets/skins/sam/autocomplete.css">
<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/datasource/datasource-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/connection/connection-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/autocomplete/autocomplete-min.js"></script>

<style type="text/css">
    #myAutoComplete {
        width:25em;
        padding-bottom:2em;
    }
</style>

The last step is to create div and put a script into calendar.get.html.ftl:

<div>
    <label for="myInput">Autocomplete:</label>
    <div id="myAutoComplete">
        <input id="myInput" type="text">
        <div id="myContainer"></div>
    </div>
</div>
<script type="text/javascript">
  YAHOO.example.BasicRemote = function() {
    var oDS = new YAHOO.util.XHRDataSource("/controllers/app/autocomplete");
    oDS.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;
    oDS.responseSchema = {
      recordDelim: "n",
      fieldDelim: "t"
    };
    oDS.maxCacheEntries = 5;
    var oAC = new YAHOO.widget.AutoComplete("myInput", "myContainer", oDS);
    return {
      oDS: oDS,
      oAC: oAC
    };
  }();
</script>

And that should be all, now let’s test it, if it works! So open http://localhost:8080/controllers/calendar and voila…

Working autocompletion

Working autocompletion

Ok, that’s all for this post, looks like it works! So you can download backup of this code somewhere around here and enjoy it on your own devbox. Keep looking forward for next stuff, maybe using facebook login with Spring social, who knows ;-).

JSP based components in Spring Surf

1

In my last blogpost we got Java backed webscripts working, now let’s try something completely different: defining page snippet as a component in .JSP. Just let’s continue with our last code, which is possible to download, but it’s not necessary, it’s possible to build it all on green meadow (aka after project in roo is created and surf installed).

First thing to do is to add dependency for jstl into Maven’s pom.xml and then update maven dependencies and refresh our project in Eclipse.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>com.springsource.javax.servlet.jsp.jstl</artifactId>
    <version>1.2.0</version>
</dependency>

Now you can get glue on Spring forums, or trust me and create new component type with JSP Renderer: it’s needed to create new directory – /WEB-INF/classes/surf/site/component-types and inside new component type configuration – test.xml.

<?xml version="1.0" encoding="UTF-8"?>
<component-type>
    <id>test</id>
    <title>Test Component Type</title>
    <description>Test Component Type</description>

    <processor mode="view">
        <id>jsp</id>
        <jsp-path></jsp-path>
    </processor>
</component-type>

Jsp-path is at this time undefined, because we haven’t created any page yet. So let’s do something with that. We need to create new template and new template instance:

roo> surf template create --path test
Created SRC_MAIN_WEBAPP/WEB-INF/templates/test.ftl
roo> surf template instance create --id test --path templates --template test
Created SRC_MAIN_WEBAPP/WEB-INF/templates/test.xml

At this time we have Freemarker template (test.ftl) and template instance (test.xml) inside directory /WEB-INF/templates. We need to edit those files. First let’s add following code into test.ftl. There are four regions defined – three of them inside template scope (already defined by installation of Surf addon) and one with page scope, which we’ll define and bind later.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>${page.title}</title>
  </head>

  <body>
    <div id="page">
      <div id="header">
        <@region id="header" scope="template" />
      </div>
      <div id="horznav">
        <@region id="horznav" scope="template" />
      </div>
      <div id="content">
        <@region id="content" scope="page" />
      </div>
      <div id="footer">
        <@region id="footer" scope="template" />
      </div>
    </div>
  </body>
</html>

Following code (template instance) is definition of components in template scope and is also located in templates directory: test.xml.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<template-instance>
  <title>test</title>
  <description>Instance of test</description>
  <template-type>test</template-type>
  <components>
    <component>
      <region-id>header</region-id>
      <url>/company/header</url>
    </component>
    <component>
      <region-id>horznav</region-id>
      <url>/navigation/horizontal</url>
    </component>
    <component>
      <region-id>footer</region-id>
      <url>/company/footer</url>
    </component>
  </components>
</template-instance>

Now we can create new page based on previously defined template-instance and add link to our new page to horizontal bar. For those actions we can use roo:

roo> surf page create --id test --path pagestest --templateInstance test
Created SRC_MAIN_WEBAPP/WEB-INF/pages/test
Created SRC_MAIN_WEBAPP/WEB-INF/pages/test/test.xml

roo> surf page association create --sourceId home --destId test
Managed SRC_MAIN_WEBAPP/WEB-INF/pages/home/home.xml

As written in roo output, directory test inside pages is created and test.xml within. This file is page configuration and we have to define our content for region defined in template. But not necessary, it’s good idea to check our work now. So let’s try to Run it on server… It’s ugly, but it works! 🙂

First try

First try

That’s cool, but our aim is to create working .jsp page. How to do that? What about simply create that page? 🙂 So let’s create test.jsp inside /WEB-INF/pages/test and fill it with some simple code:

<%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt'%>

<%@ page import="java.util.*"  %>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>

<h1>Test jsp</h1>

<%
  String someText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

  List<String> l = new ArrayList<String>();
  l.add("Maecenas iaculis odio id eros fermentum non tempus erat interdum.");
  l.add("Sed mi orci, dignissim vitae cursus hendrerit, congue sed odio. ");
  l.add("Vivamus quam diam, dapibus sit amet placerat a, tempus at magna.");

  session.setAttribute("someText", someText);
  session.setAttribute("l", l);
%>

<p>${someText }</p>

<c:forEach var="x" items="${l }" >
    <p>${x}</p>
</c:forEach>

That’s our page. Now we need to connect it with previously created component type – /WEB-INF/classes/surf/site/component-types/test.xml. In time of creation we omit jsp-path, so fill it up now:

<jsp-path>/WEB-INF/pages/test/test.jsp</jsp-path>

Last thing to do is to put our shiny new component-type into page. In template we defined region, which is filled in page scope. That’s that components section in page config – /WEB-INF/pages/test/test.xml. It’s good idea to add some title and some styling like border and background thanks to chrome element:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<page>
  <id>test</id>
  <title>test</title>
  <template-instance>test</template-instance>
  <authentication>none</authentication>
  <components>
    <component>
      <region-id>content</region-id>
      <component-type-id>test</component-type-id>
      <chrome>box</chrome>
      <title>JSP inside</title>
    </component>
  </components>
</page>

After rebuild and redeploy we have our jsp component working, as you can see at http://localhost:8080/webscripts/test. Congratulations, good work!

Final application look

Final application look

Ah, in case you got lost, there is package with working sourcecode for this whole example.

Freemarker templates and java backed webscripts

1

Wondering about output to freemarker template from java backed webscript in Spring Surf? You’re on the right place, it’s simple so I’ll try to describe it on a few lines. For first I suppose some prerequisites you have:

Ok, let’s get it done quickly! Create new directory, for example webscripts. Go into it, fire up roo, create a new project, install surf extension into it and create an Eclipse project:

project --topLevelPackage cz.shmoula.webscripts
surf install
perform eclipse

Now you should have base skeleton of our future app (you can also download it here) and you can import it into SpringSource Tool Suite.

Webscripts are located in src/main/webapp/WEB-INF/webscripts folder, so open that folder and create two files: example.get.html.ftl (template) and example.get.desc.xml (description).

<p>logged user: ${userId}</p>
<webscript>
      <shortname>Example</shortname>
      <description>Sample java backed webscript</description>
      <url>/example</url>
</webscript>

Now we have to create our java source code. It’s not bad idea to put webscripts to their own package, for example webscript. In that package create a new class, which extends org.springframework.extensions.webscripts.AbstractWebScript – Example. By doing that we have to implement an execute method, which is called, when webscript is executed:

@Override
public void execute(WebScriptRequest req, WebScriptResponse res)
    throws IOException {
}

Let’s fill that method. We need a model map, which holds values as pair (String)key – (Object)value. For our desired function we also need to get HttpServletRequest:

Map<String, Object> model = new HashMap<String, Object>();
HttpServletRequest httpRequest = ServletUtil.getRequest();

Now to fill up model (aka our function). Let’s find out if there is logged in user and if so, write out it’s userId:

if(AuthenticationUtil.isAuthenticated(httpRequest)){
      model.put("userId", AuthenticationUtil.getUserId(httpRequest));
}else{
      model.put("userId", "guest");
}

Final step is to put out our model. We need to get writer and renderTemplate, which we specified by its path (and also flush and close our writer):

Writer writer = res.getWriter();
String templatePath = "webscripts/example.get.html.ftl";
renderTemplate(templatePath, createTemplateParameters(req, res, model), writer);

writer.flush();
writer.close();

Last thing we have to do is to let Surf know about our shiny new webscript. You can add new bean directly inside applicationContext, but it’s not bad idea to keep them separately. So in src/main/webapp/WEB-INF/config create new Spring Bean Definition file – custom-webscripts-config.xml and put inside new bean definition:

<bean id="webscript.webscripts.example.get" class="cz.shmoula.webscript.Example" parent="webscript"/>

Now we have to import that new config: in the same directory is surf-config.xml file, so let’s add there new import:

<import resource="custom-webscripts-config.xml"/>

At this time we can run our project and visit http://localhost:8080/webscripts/example, which shows following page:

Image and video hosting by TinyPic

It’s possible to login (if you have set up user factory) as an Alfresco user and after that another userId is shown. I’m planning to write new blogpost about custom user factory and stuff like that, so be patient please. Finally, you can download source code for this example at this link. Structure of project is shown at following screenshot (note that red dots – those are modified files):

Image and video hosting by TinyPic

Finally, try to experiment with some examples from Alfresco wiki and look forward to next blogpost.

Go to Top