Skip navigation
1 2 3 4 Previous Next

brunogh

48 posts

The call for papers for JavaOne 2010 Brazil is open! Do not miss the chance!

To submit, fill the form at: http://www.openworldlad.com.br/java-one-pt(portuguese) or http://www.openworldlad.com.br/java-one-en(english).

Tracks:

  1. Core Java Platform
  2. Desktop Java
  3. Java EE Web Profile and Platform Technologies
  4. Enterprise Service Architectures and the Cloud
  5. JavaFX and Rich User Experience
  6. Java ME and Mobile
  7. Java for Devices, Card and TV
  8. The Java Frontier

 

The confere will happen at December 7 - 9, 2010 in São Paulo. More info at http://www.oracle.com/br/javaonedevelop/index.html.

 

Thanks,

Bruno Ghisi

Hello guys,

This post reflects a thought around a case that I have been experiencing. There a lot of things that involves implementing a spec and one of them is that you need to guarantee that you are not exposing more than it is available on the Javadoc.

There are a few static factory methods and no constructors, means public and protected, in our Javadoc scenario. So, you need to guarantee, by code, that there are only private constructors and nobody will cut them off.

So we create a unit test that assures there are not other constructors then private. Reflection is used for finding the constructors array and if there are no protected and public, zero should be returned.

FooTest.java:

@Test

public void testThereAreOnlyPrivateConstructors() { 

   Constructor[] constructors = Foo.class.getConstructors();

   assertEquals(0, constructors.length);

}

Foo.java:

public class Foo {

   private Foo() { }

   public static Foo createFoo(int s) {

     //do something

     return new Foo();

   }

   ...

}

The thing is pretty much obvious, but the idea here was to shown something that does not happens everyday, but applies for a few interesting scenarios.

Cheers,
Bruno Ghisi

Hello guys,

I have just released a plugin for Scripting in Grails. It basically let you create Groovy scripts as CRUDs, so you can use them for dynamic behaviors. This is a first release, so feel free to send feedback for future improvements.

http://www.grails.org/plugin/scripting

If you want to learn more about how to create plugins for Grails, check this link.

Merry Xmas and Happy New Year!!!

Cheers,

Bruno Ghisi

Today we are gonna talk about how to create a Java application for Digital TV that integrates with Twitter. Note that the demo will be based on the basic Java DTV stack, without any specific middleware definitions, so feel free to add UI later.

phoneMe Advanced is the basic stack (CDC/FP/PBP) for DTV middlewares. I started looking at a Twitter library in Java and found an interesting one called Twitter4J (http://twitter4j.org). Twitter4J has a target compilation for Java 1.4, which is needed, because phoneME Advanced is a subset of Java 1.4 (does not have some packages and methods) compatible with the language syntax. Most of the others libraries were only for 1.5.

  1. Download phoneME Advanced (http://phoneme.dev.java.net) and compile it (http://wiki.java.net/bin/view/Mobileandembedded/PhoneMEAdvanced).
  2. Create a new Java Project and add basis.jar and btclasses.zip in the classpath (it will be generated after compiling phoneMe Advanced). Also remove the default JRE at Java Build Path->Libraries, if you are using Eclipse.
  3. Download Twitter4J (http://twitter4j.org/en/index.html) and add it to the project classpath.

Create a TwitterXlet.java class like above. Xlet is an interface that is needed to be implement, so AMS (Application Management System) can run it in a sandbox.

import java.util.ArrayList;
import java.util.List;
import javax.microedition.xlet.Xlet;
import javax.microedition.xlet.
XletContext;
import javax.microedition.xlet.XletStateChangeException;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import com.sun.xlet.XletContextImpl;

public class TwitterXlet implements Xlet {

    protected XletContextImpl context;

    public void initXlet(XletContext xletContext)
            throws XletStateChangeException {
        context = (XletContextImpl) xletContext;
    }

    public void destroyXlet(boolean unconditional)
            throws XletStateChangeException {
    }

    public void pauseXlet() {
    }

    public void startXlet() throws XletStateChangeException {
        List result = this.search("#java");
        for (int i = 0; i < result.size(); i++) {
            Tweet tweet = (Tweet) result.get(i);
            System.out.println(tweet.getFromUser() + " " + tweet.getText());
        }
    }

    public List search(String s) {
        List toReturn = new ArrayList();
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            Query query = new Query(s);
            QueryResult result;
            result = twitter.search(query);
            toReturn = result.getTweets();
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        return toReturn;
    }
}

Create a twitter.policy file that will be passed to override on execution for test purposes:
grant {
    permission java.security.AllPermission;
};


Now, note that you will need to add xerces.jar (http://xerces.apache.org/mirrors.cgi) into the execution classpath when invokes the XletRunner to run the TwitterXlet. This is because Twitter4J depends on org.xml.sax package and the stack does not provide implementation.

To run the Xlet application:
${PHONEME_PATH}/cdc/build/
linux-x86-generic/bin/cvm -Djava.security.policy=${POLICY_PATH}/twitter.policy com.sun.xlet.XletRunner -name TwitterXlet -path${APP_PATH}/bin:${APP_PATH}/lib/twitter4j-core-2.1.6.jar:${APP_PATH}/lib/xerces.jar

Output (a lot fo people from all around the world is quoting Java!):
@@XletRunner starting Xlet TwitterXlet
[Mon Nov 22 12:59:10 GMT-03:00 2010]Will use class twitter4j.internal.logging.
StdOutLoggerFactory as logging factory.
[Mon Nov 22 12:59:10 GMT-03:00 2010]Will use twitter4j.internal.http.HttpClientImpl as HttpClient implementation.
darksage07 Alguem me pode explicar ond é que ta o erro neste sniippet k fiz em #java http://pastebin.com/bzP9pB8e ?
baselogic #java #javaee I can agree with everything except for "Python 2.5 is old". Its not old, its stable for product... http://bit.ly/bCKiS7 pt
baselogic #java #javaee Reconfiguring mac for heavy JBoss, J2EE, work. #mac #java# RT @bitsmonkey:  http://bit.ly/cX1ycSpt
baselogic #java #javaee Configuration Management Database - You can move forward even if you don't want a complete CMDB... http://bit.ly/bX98l9pt
baselogic #java #javaee Forgot url for mobile dev with spring http://bit.ly/bxhyxb# RT @vdandre:  http://bit.ly/a4xR3Vpt
baselogic #java #javaee FREE Red Hat Webinar - Insight into Performance Improvements JBoss Enterprise Platforms- Nov 23... http://bit.ly/dqbtOa pt
top_java_jobs Myspace Feed System Replica by creativefuse: I am looking for a feed system similar to the New Myspa... http://bit.ly/cNnDAo#Java #Jobs
ruglax pregunta de novato, en #java, para una aplicacion #JavaSE, cual es la forma correcta de ,anejar usuarios?
enterprisejava #java #javaee Will the "NoSQL" fad thrive or end?# RT @riyaaz:  http://bit.ly/a0qmOe pt /via @baselogic:  http://bit.ly/c0JxMI
enterprisejava #java #javaee JBoss Application Server 7 looks shockingly good (Asylum #14 podcast) - http://su.pr/1q47gS#RT...... http://bit.ly/asQQvS
baselogic #java ???????? iOS 4.2 ?????? ???????: iPhoneRoot.com??????? ???????? Apple ????????? ?????-?????, ? ??????? ... http://bit.ly/9XUKB5 jb
baselogic #java Google datastore discussion: The Disco BlogGoogle’s datastore, known as Bigtable, is a column-oriented ... http://bit.ly/dgGgLD jb
baselogic #java ??? ??????????? iOS 4.2 ??? iPhone/iPad ? 15-???????? ?????: iPhoneRoot.com???? ?? ??? ???? ?????? ????... http://bit.ly/bex7Ii jb
baselogic #java 2010? 11? 22?, ????: ???? ?? ??? [??™]2010-11-22 16:00:21 ???. ^^ infinitest…  ?? ~ ????~!! by ... http://bit.ly/bY953I jb
baselogic #java Agile Testing UK – plans for the future: Gojko AdzicAt the BDD and Agile Testing exchange conference on...http://bit.ly/cp0YeT jb


ps: Thanks to Yusuke Yamamoto for the support in the users list. Great project!


Have fun!
Bruno Ghisi


 

My masters colleague, Guilherme Hobold, and his friend, Elinton Machado, have created a very interesting project for helping Java ME applications with dependency injection. Actually, it is not only for Java ME (CLDC), but because of there is no reflection, they have done some magic to make it work in a nice way.

The project is called DIME, which means Dependency Injection for Java ME. Basically it has a XML to configure the beans (it depends on kXML lib for parsing), a container to get the beans and the classes have to implemented a Bean interface that provides access to the hash table that is used to set the correct values. The XML file uses the same notation as Spring.

Here is some sample code that I got from the project page.

XML file (also supports map and other types).
<?xml version="1.0"?>
<beans>
      <import resource="other_beans.xml" />

      <bean id="fooSet" class="test.collection.FooList">
            <property name="elements">
                  <set>
                        <value>element1</value>
                        <value>element2</value>
                  </set>
            </property>
      </bean>

      <bean id="Foo" class="test.Foo">
            <property name="filename">
                  <value>movies2.txt</value>
            </property>
            <property name="fooSet" ref="fooSet"/>
      </bean>
</beans>

Make a bean:
import java.util.Hashtable;
import org.dime.Bean;
import test.collection.FooList;

public class Foo extends FooAbstract implements Bean {

      private String filename;
      private FooList fooSet;

      public String getFilename() {
            return filename;
      }

      public void setProperties(Hashtable properties) {
            filename = (String)properties.get("filename");
            fooSet = (FooList)properties.get("fooSet");
      }
}


Load the XML file and get the bean:
BeanContainer container = new ClassPathXmlBeanContainer("file.xml");
Foo foo = (Foo)container.getBean("Foo");
System.out.println(foo.getFilename());



Very nice job! Take a look in the project page for more information. Take a try!

http://dime.dev.java.net

Cheers,
Bruno Ghisi

A long time without blogging, I have been busy working with DTV applications and GRails... this post goes with the second topic...

Have you already installed Spring Security (Acegi) pluginin Grails? Do you want to allow logins with the email also - like Twitter, SlideShare, etc - and not only with the default username?

Here is the simple way to make it to work:

1 - Implement an AuthenticationProvider (EmailAuthenticationProvider) in src/groovy:

import org.springframework.security.*
import org.springframework.security.
providers.*
import org.springframework.security.
userdetails.*
import org.springframework.security.
context.*
import org.codehaus.groovy.grails.
plugins.springsecurity.GrailsUserImpl
import User

class EmailAuthenticationProvider implements AuthenticationProvider {

    def authenticateService

    Authentication authenticate(Authentication customAuth) {
               User.withTransaction { status ->
                    User user = User.findByEmail(customAuth.
principal)
                    if(user) {
                        if (user?.passwd == authenticateService.
encodePassword(customAuth.credentials)) {
                            GrantedAuthorityImpl[] authorities = user.authorities.collect {new GrantedAuthorityImpl(it.
authority)}
                            def userDetails = new GrailsUserImpl(user.email, user.passwd, true, true, true, true, authorities, user)
                            def token = new UsernamePasswordAuthentication
Token(userDetails, user.passwd, userDetails.authorities)
                            token.details = customAuth.details

                            return token
                        }else throw new BadCredentialsException("Log in failed - identity could not be verified");
                    }else {
                        return null
                    }
               }
    }

    boolean supports(Class authentication) {
        return true
    }
}



2 - Set this provider bean in grails-app/conf/spring/resources.xml file:

import EmailAuthenticationProvider
beans = {
     emailAuthenticationProvider(EmailAuthenticationProvider) {
        authenticateService = ref("authenticateService")
     }
}



3 - Add your email provider in the stack in grails-app/conf/SecurityConfig.groovy fi(DaoAuthenticationProvider is the default one that uses the username):


providerNames = ['emailAuthenticationProvider', daoAuthenticationProvider','anonymousAuthenticationProvider', 'rememberMeAuthenticationProvider']

 

4 - Done! Try now to login with the username or email.

 

Have fun!

Cheers,
Bruno Ghisi


ps: Felipe Gaúcho, you were a brilliant guy. We are going tomiss you.

LWUIT was created in the Java ME world to solve an old problem related to the different UI components rendering by different mobiles. This introduction to MIDP UI can help you to understand. 

From the LWUIT project:

Writing appealing cross device applications today in Java ME is challenging. Due to implementation differences in fonts, layout, menus, etc. the same application may look and behave very differently on different devices. In addition much of the advanced UI functionality is not accessible in LCDUI and requires the developer to write very low level "paint" type code. The Lightweight UI Toolkit was developed to address these issues

LWUIT offers the same high level UI components provided in LCDUI, but it does guarantee how it is renderized. But what is the problem? Why this post?! LWUIT in Java DTV is part of the specification, available through com.sun.dtv.lwuit package.

com.sun.dtv.lwuit from Java DTV specification:

Main widget package containing the component/container "composite" similar both in terminology and design to Swing/AWT. Unlike Swing/AWT a full windowing system is not applicable in this case and forms are placed using a DTVContainer passed into Plane and Screen abstractions.

So, how the industry will implement LWUIT components in Ginga?! Are we going to have a new LWUIT project to solve future LWUIT problems in DTV brazilian context? Is Java DTV LWUIT a real spec or just marketing?


Have a nice week!
Bruno Ghisi  
brunogh

Java DTV 1.2.1 is out! Blog

Posted by brunogh Oct 2, 2009

The new version of Java DTV specification, 1.2.1, was released at http://www.forumsbtvd.org.br/materias.asp?id=200.

Java DTV was created in order to prevent some royalty issues from some MHP APIs, like DAVIC e HAVI, in the Ginga-J subsystem of the Brazilian DTV middleware specification, which is also called Ginga. For more information around this soap opera, check this old blog entry.

So, what are the next steps? Java DTV will become a JSR?

Thanks,

Bruno Ghisi  

If you want to translate your message files for a couple of different languages, but you do not have money, do not have time, do not have language specialists friends or do not have anything else to help you, we have a solution... actually we got a "use at your own risk" solution!

Here are the steps:

  • Download google-api-translate-java-0.53.jarand use it in the classpath.
  • Configure the default input file and output files (languages) in MessagePropertyGenerator.java util class, which is detailed above. In my example, I have setted a portuguese property file - which is detailed above as well- and generated an english, german and spanish file with Google translations.
  • Compile and run it!

MessagePropertyGenerator.java

 import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Vector; import com.google.api.translate.Language; import com.google.api.translate.Translate; import java.io.FileInputStream; public class MessagePropertyGenerator { private static String baseLanguage = Language.PORTUGESE; private static String basePropertyFileName = "/home/brunogh/NetBeansProjects/I18NGenerator/src/messages_pt_BR.properties"; private static String enconding = "ISO-8859-1"; private static String fullPathToWriteTargetFiles = "/home/brunogh/NetBeansProjects/I18NGenerator/src/"; private static String[][] targetLanguages = { {Language.ENGLISH,"messages_en_US.properties"}, {Language.SPANISH,"messages_es.properties"}, {Language.GERMAN, "messages_de.properties"}}; public static void main(String[] args) { try { String currentLanguage = null; String currentFileName = null; String translatedText = null; BufferedReader d = null; for (int i = 0; i < targetLanguages.length; i++) { d = new BufferedReader(new InputStreamReader(new FileInputStream(basePropertyFileName),enconding)); currentLanguage = targetLanguages[i][0]; currentFileName = targetLanguages[i][1]; String s = ""; StringBuffer sb = new StringBuffer(); Vector notTranslated = new Vector(); while ((s = d.readLine()) != null) { if ((!s.trim().equals("")) && (!s.startsWith("#"))&& (s.contains("="))) { String[] keyValue = s.split("="); try { translatedText = Translate.translate(keyValue[1], baseLanguage, currentLanguage); translatedText = replaceParenteses(translatedText); sb.append(keyValue[0] + "=" + translatedText+ "\n"); System.out.println(keyValue[0] + "="+ translatedText); } catch (Exception ex) { sb.append(s); notTranslated.add(s); ex.printStackTrace(); } } else { sb.append(s + "\n"); } } createPropertyFile(sb, currentFileName); printNotTranslated(notTranslated); } } catch (Exception e) { e.printStackTrace(); } } private static String replaceParenteses(String translatedText) { //TODO rewrite to be a generic solution return translatedText.replace("(0)", "{0}").replace("(1)", "{1}").replace("(2)", "{2}"); } private static void createPropertyFile(StringBuffer sb, String currentFileName) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(fullPathToWriteTargetFiles + currentFileName); fos.write(sb.toString().getBytes(enconding)); fos.flush(); fos.close(); } private static void printNotTranslated(Vector notTranslated) { System.out.println("Not translated:"); for (String string : notTranslated) { System.out.println(string); } System.out.println("-=-=-=-="); } } 

messages_pt_BR.properties

 test.helloworld=Ol

After almost one year, Brazil's Digital Television Forum (SBTVD) has finally fixed the royalty confusion with Sun's help. We now have a royalty-free/open source specification that substitutes the GEM API in the Brazilian middleware Java subsystem (Ginga-J). This specification seems to be using LWUIT for the UI. Download the javadoc here.

I do still have a few questions. How this specification will evolve since it is not standardized as a JSR in the JCP? Is there any tools/emulators to play with the specification? OpenGinga?

Finally, congrats for the people that have worked on that. Open source did one more point! You can check the announcement in portuguese here and find a nice recap in this Rob Glidden's blog entry.

Cheers!
Bruno Ghisi 

Disclaimer: This post - and all the old and new ones - express my own opinion and does not reflect the opinion of my actual employee.

This post is simple. In the company that I am working, we have some local area books that have a different control. Because they are out of the normal process, we do not have anything to control the borrowing. That can cause a problem, because sometimes people can accidentally forget that borrowed a book (sometimes I cannot remember what day is in the week and I think I work with crazier guys). So, the problem is simple and the use case will be too. Basically, someone that is responsible for the books will rent them for the team. Why not develop this fast application using Grails?!Grails, which means Groovy on Rails, is an "agile" framework that uses Spring and Hibernate with a lot of code by convention. NetBeans 6.5 has an interesting support for its development, you can find instructions on how to start here. Anyway, I decided to start programming the application described using gedit and console in order to learn from the beginning and actually type the Gant commands. It took me a few hours to set a first version of the application and I am definitely still learning, but I can guarantee fore sure that Grails is very fast and fun. The application has two domain classes, a Book, that represents the instance itself (we usually do not have copies), and a Rent, that represents the act of borrowing the book. The application also contains other domain classes (User, Role, Requestmap) that came from the Acegi Plugin installed, which will manage permissions and URLs. All those domain classes have its controllers and views. I also have added a AdminController for the admin area and HomeController for the default home page, mapped in grails-app/conf/UrlMapping.groovy. The index home view uses a home decorator available at /grails-app/views/layout, specified by the meta name="layout" content="home" tag in its gsp page. The application uses a lot of scaffolding for the CRUDs and also have loved the dynamic finders to create the queries. Finally, have generated the war and deployed it on a Tomcat server using the production configuration with a MySQL database, specified in grails-app/conf/DataSource.groovy file. You can download BookBorrowing here. Feel free to modify and do whatever you want. Home - list all the availables books for borrow and has a search 

screenshot.png

Admin area 

screenshot2.png

Rent view in the Admin area - "Devolver" means return this book, "Devolvido" means list of returned books and "Emprestados" means the currently borrowed. Need to i18n, gonna do it soon. 

screenshot3.png

Cheers! Have fun!!!
Bruno Ghisi  
Are you aged 26 or younger? What are you waiting to travel for free for Jazoon'09 and meet a lot of cool people?! Submit your technical talk before February, 28 at http://jazoon.com/en/contribute/rookie.html. The top 3 rookies will be invited to go there and give a 20 minutes talk. Wow! All Java conferences should copy this awesome initiative, Jazoon definitely rocks! These young guys need your support to become the speakers from tomorrow! http://jazoon.com/dms-static/8a95b0e6-75d3-4896-9491-8acafd65af64/Jazoon%20Rookie.jpgCheers! Bruno Ghisi  
brunogh

A rewrite for Puzzle 17 Blog

Posted by brunogh Dec 24, 2008
A rewrite for Puzzle 17, from Java Puzzlers :) Compile it and run. Main.java \u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0063\u006C\u0061\u0073\u0073\u0020\u004D\u0061\u0069\u006E\u0020\u007B\u000A\u0020\u0020\u0020\u0020\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0020\u0061\u0072\u0067\u0073\u0029\u0020\u007B\u000A\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u004D\u0065\u0072\u0072\u0079\u0020\u0058\u006D\u0061\u0073\u0021\u0020\u0048\u0061\u0070\u0070\u0079\u0020\u004E\u0065\u0077\u0020\u0059\u0065\u0061\u0072\u0021\u0022\u0029\u003B\u000A\u0020\u0020\u0020\u0020\u007D\u000A\u007D All the best for you and your family! Enjoy the end of the year! Looking for 2009! M3DD begins in 4 weeks! Bruno Ghisi  

Have you seen this unofficial Java API for Google Translator? So, I was thinking that it could be interesting to mix this stuff with Java Speech API (JSAPI).

JSAPI was divided to support two things: speech recognizers and synthesizers.Speech synthesis is the process of generating human speech from written text for a specific language. Speech recognition is the process of converting human speech to words/commands. This converted text can be used or interpreted in different ways(interesting and simple definition from this article).

It seems that there are not too many open source projects that cares about the recognizer part. I have found a very interesting one called Sphinx, but did not have time to try it yet. I was thinking how cool would be to have an open source software to make possible a talk between two different people, like you say something in a language, it translates to another language and say that. Have anybody seen anything like that? Non commercial? For voip?

So, I work in part of a demo, but only with the the synthesizer part, the text input is manually. I used FreeTTS for that. Basically this piece of code gets an word input in Portuguese, translates it to English and then say the word.

package speech;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) {
        VoiceManager voiceManager = VoiceManager.getInstance();
        Voice voice = voiceManager.getVoice("kevin16");
        voice.allocate();

        String text = null;
        do {
            try {
                System.out.println("Type a word in Portuguese and listen it in English -> ");
                text = new BufferedReader(new InputStreamReader(System.in)).readLine();
                voice.speak(Translate.translate(text, Language.PORTUGESE, Language.ENGLISH));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } while (!text.equals("!quit"));

        voice.deallocate();
        System.exit(0);
    }
}

If you got excited to work in an open source project like that, go ahead and write something! I can guarantee your fun!

Have a nice week!
Bruno Ghisi  
brunogh

More Quick Updates... Blog

Posted by brunogh Oct 1, 2008