viernes, 6 de febrero de 2015

jconsole and VisualVM over ssh tunnel on EC2 for Tomcat 7 using JMX

Hi, today I will talk about how to do a tunnel using ssh in order to monitor Apache Tomcat 7 using JMX in four simple steps.

Let's suppose:

  • Your Apache Tomcat 7 server is installed on Amazon EC2 platform
  • You want to monitor Tomcat from your Mac OS computer (or Linux) without having installed jconsole on EC2

Then, do the following.

1) On the EC2 server side assign the CATALINA_OPTS variable (and export it):

$CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"

2) Restarts Apache Tomcat

3) Start the ssh tunnel:

ssh -D9999 -i your_keyfile.pem ec2-user@your_domain_name.com

4) On the client side, open a terminal and execute the following:

jconsole -J-DsocksProxyHost=localhost -J-DsocksProxyPort=9999 service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi

That's it!!

PS. Remember to adjust it according the ports you want
      For VisualVM, do not forget to configure the SOCKS proxy and pay attention to the option No Proxy Hosts in case of localhost



jueves, 8 de mayo de 2014

A simple way to determine if a String could be an integer

There are a lot of ways to check if a String could represent an integer value. I will show you two very simple and yet fast methods:

Method 1

    public final static boolean isInteger(String in)
    {
        char c;
        int length = in.length();
        boolean ret = length > 0;
        int i = ret && in.charAt(0) == '-' ? 1 : 0;
        for (; ret && i < length; i++)
        {
            c = in.charAt(i);
            ret = (c >= '0' && c <= '9');
        }
        return ret;
    }


Method 2 (modified version of method 1)

    public static boolean isInteger(String in)
    {
        if (in != null)
        {
            char c;
            int i = 0;
            int l = in.length();
            if (l > 0 && in.charAt(0) == '-')
            {
                i = 1;
            }
            if (l > i)
            {
                for (; i < l; i++)
                {
                    c = in.charAt(i);
                    if (c < '0' || c > '9')
                        return false;
                }
                return true;
            }
        }
        return false;
    }


Method 3 

    static final byte[] b = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    public final static boolean isInteger(String in)
    {
        char c;
        int length = in.length();
        int i = 0;
        if (length > 0 && in.charAt(0) == '-')
            i = 1;
        if (i >= length)
        {
            return false;
        }
        for (; i < length; i++)
        {
            c = in.charAt(i);
            if (b[c & 0xff] == 0)
                return false;
        }
        return true;
    }



I hope this information is useful.

PS. Be aware that all of these will say that very large strings (with valid big integers) are true, so if you just try to convert them to Integers, an Exception could be thrown.

domingo, 4 de mayo de 2014

Multiple column list using HTML (ul and li)

I know that you could find a lot of ways to show columns using HTML,  but sometimes for most of those ways you need a "deep"  knowledge of CSS, if you just know the very basic stuff of CSS and HTML, then this is for you. Fast and easy.

The idea is having a multicolumn list, using ul and li tags (and just a little bit of CSS).
Let's suppose you have the following data and you want them to show as a column for every category:

id  name         category
--------------------------
1   Antena       Exterior
2   Emblema      Exterior
3   Llantas      Exterior
4   Luces        Exterior
5   Estéreo      Interior
6   Tapetes      Interior
7   Encendedor   Interior
8   Gato         Accesorio
9   Extintor     Accesorio
10  Herramientas Accesorio
11  Claxon       Cofre
12  Batería      Cofre
13  Filtro aire  Cofre


You want them to look like this:

Exterior   Interior    Accesorio     Cofre
---------  ----------  ------------  -----------
Antena     Estéreo     Gato          Claxon
Emblema    Tapetes     Extintor      Batería
Llantas    Encendedor  Herramientas  Filtro aire
Luces

So, the HTML code could be as easy as this:

<ul style="float:left;list-style-type: none;">Exterior<hr>
    <li>Antena</li>
    <li>Emblema</li>
    <li>Llantas</li>
    <li>Luces</li>
</ul>

<ul style="float:left;list-style-type: none;">Interior<hr>
    <li>Estéreo</li>
    <li>Tapetes</li>
    <li>Encendedor</li>
</ul>

<ul style="float:left;list-style-type: none;">Accesorio<hr>
    <li>Gato</li>
    <li>Extintor</li>
    <li>Herramientas</li>
</ul>

<ul style="float:left;list-style-type: none;">Cofre<hr>
    <li>Claxon</li>
    <li>Batería</li>
    <li>Filtro aire</li>
</ul>




There you have It!.

I hope this is useful for you.

martes, 1 de abril de 2014

Signing Qt5 (5.2.0) Applications in Mac OSX Mavericks

I was trying to sign an application that We developed with Qt5 (medicalmanik.com) and due to the not so clear documentation you find out there, I decided to publish the way I could complete this task (I tried some procedures I found on different sites without success -that's why I am publishing this).

First of all let me tell you that I just basically modified one script I found on Internet (and use another one as is) and adapted it to my needs, so you just have to edit some lines in It and that's it!

What It is important to notice is that if you want to distribute your application out of the AppStore you will need a Developer ID Application certificate (not the Mac Developer -this is just for testing).

OK, let's begin...

1) Copy, paste and save to a file the following code, or download it  from  https://gist.github.com/kainjow/8059407 (macdeployqt_fix_frameworks.rb). There is not need to modify it.


#!/usr/bin/env ruby

# Copies missing Info.plist files for a .app's Qt frameworks installed
# from macdeployqt. Without the plists, 'codesign' fails on 10.9 with
# "bundle format unrecognized, invalid, or unsuitable".
#
# Example usage: 
# ruby macdeployqt_fix_frameworks.rb /Users/me/Qt5.2.0/5.2.0/clang_64/ MyProgram.app
#
# Links:
# https://bugreports.qt-project.org/browse/QTBUG-23268
# http://stackoverflow.com/questions/19637131/sign-a-framework-for-osx-10-9
# http://qt-project.org/forums/viewthread/35312

require 'fileutils'

qtdir = ARGV.shift
dotapp = ARGV.shift

abort "Missing args." if !qtdir || !dotapp
abort "\"#{qtdir}\" invalid" if !File.exists?(qtdir) || !File.directory?(qtdir)
abort "\"#{dotapp}\" invalid" if !File.exists?(dotapp) || !File.directory?(dotapp)

frameworksDir = File.join(dotapp, 'Contents', 'Frameworks')
Dir.foreach(frameworksDir) do |framework|
  next if !framework.match(/^Qt.*.framework$/)
  fullPath = File.join(frameworksDir, framework)
  destPlist = File.join(fullPath, 'Resources', 'Info.plist')
  next if File.exists?(destPlist)
  srcPlist = File.join(qtdir, 'lib', framework, 'Contents', 'Info.plist')
  abort "Source plist not found: \"#{srcPlist}\"" if !File.exists?(srcPlist)
  FileUtils.cp(srcPlist, destPlist)
end

2) Create a file named macdeployqt.sh (this will call macdeployqt_fix_frameworks.rb and macdeployqt ) and copy, paste and edit the following code (posted by Sarah Jane Smith on https://bugreports.qt-project.org/browse/QTBUG-23268). Modify It according to your needs (take a look at the PATHS).


# Create a temporary copy of the app for deploy & signing
# This must not be previously signed/sandboxed
# Include the .app suffix

APP_NAME=$1

QT5_CLANG=/Users/hectorsuarez/Aplicaciones/Qt5.2.0/5.2.0/clang_64
QT5_BIN=$QT5_CLANG/bin


#EXT_SIGN_CERT="Mac Developer: Hector Suarez Barenca"
EXT_SIGN_CERT="Developer ID Application: Barenca Networks"

# This will create a temporary directory
BUILD_TMP=~/tmp
if [ -d $BUID_TMP ]
then
echo
echo "###"
echo "### Cleaning directory... $BUILD_TMP/$APP_NAME ###"
echo "###"
echo
### Borrar versión previa
rm -rf $BUILD_TMP/$APP_NAME
else
    mkdir -p $BUILD_TMP
fi

echo "### Copy $APP_NAME to $BUILD_TMP"
echo

### Copy the .app to a temporary location
cp -R $APP_NAME $BUILD_TMP

TMP_APP=$BUILD_TMP/$APP_NAME

QT_FMWK_VERSION="5"
QT_FMWKS="QtCore QtGui QtPrintSupport QtWidgets QtMultimedia QtMultimediaWidgets QtNetwork QtSql QtScript QtWebKitWidgets QtOpenGL QtPositioning QtQml QtQuick QtSensors QtWebKit"

echo "### Deploying Qt ${QT_FMWK_VERSION}..."
echo 
$QT5_BIN/macdeployqt $TMP_APP $VERBOSE_MACDEPLOY_QT

echo "Patching Qt frameworks..."

## Set the right PATH 
~/Aplicaciones/macdeployqt_fix_frameworks.rb $QT5_CLANG $TMP_APP

for FMWK in $QT_FMWKS; do
    FMWK_PATH="${TMP_APP}/Contents/Frameworks/${FMWK}.framework"
    mv -v "${FMWK_PATH}/Resources" "${FMWK_PATH}/Versions/${QT_FMWK_VERSION}/."
    (cd "${FMWK_PATH}" && ln -s "Versions/${QT_FMWK_VERSION}/Resources" "Resources")
    (cd "${FMWK_PATH}/Versions" && ln -s "${QT_FMWK_VERSION}" "Current")
    perl -pi -e "s/${FMWK}_debug/${FMWK}/" "${FMWK_PATH}/Resources/Info.plist"
done


echo "Codesigning..."
for FMWK in $QT_FMWKS; do
    FMWK_PATH="${TMP_APP}/Contents/Frameworks/${FMWK}.framework"
    /usr/bin/codesign --verbose \
        --sign "$EXT_SIGN_CERT" \
        "${FMWK_PATH}/Versions/5"
done

for PLGN in $(find $TMP_APP -name "*.dylib"); do
    /usr/bin/codesign --verbose \
        --sign "$EXT_SIGN_CERT" \
        ${PLGN}
done

echo
echo "### Trying to sign $APP_NAME"
echo
/usr/bin/codesign --verify --verbose \
    --sign "$EXT_SIGN_CERT" \
    $TMP_APP

echo ""
echo "### Confirming \"Registered Developer\" codesiging of app"
codesign --verify --verbose=4 $TMP_APP

echo ""
echo "### Confirming codesigning app, frameworks & plugins for GateKeeper"
spctl --verbose=4 --assess --type execute $TMP_APP



3) Execute macdeployqt.sh  and enjoy It!



I hope this works for you.  Best regards.


PS. I tested these scripts with Qt 5.2.0
      Thanks to those that take time to help others


References:
https://gist.github.com/kainjow/8059407
https://bugreports.qt-project.org/browse/QTBUG-23268

https://developer.apple.com/library/mac/documentation/IDEs/Conceptual/AppDistributionGuide/DistributingApplicationsOutside/DistributingApplicationsOutside.html

http://stackoverflow.com/questions/19637131/sign-a-framework-for-osx-10-9

http://stackoverflow.com/questions/7697508/how-do-you-codesign-framework-bundles-for-the-mac-app-store

http://www.copyquery.com/productsigned-mac-app-not-installing-in-computers-that-are-not-mine/

sábado, 16 de febrero de 2013

How to remove iPhoto faces with a shell script

Now I will show you a very simple (but yet effective) way to remove the iPhoto faces with a shell script (It seems that iPhoto does not have an option to disable this feature -that's ridiculous!).

1) Open a Terminal (cmd space and then type Terminal )
2) Type vi  and then press i
3) Copy and paste the following code:

#!/bin/bash 
mdfind 'kMDItemDisplayName == "IMG_*face*.jpg"'|awk '{print "rm -f \""$0"\""}'>rmfaces 
chmod 755 rmfaces
./rmfaces 
rm rmfaces 
echo "It's done!"

4) Press  and then type :x , choose the filename (byefaces) and hit
5) Once you are in the terminal prompt again, type 

    chmod 755 byfaces 

5) That's all!!!! 
6) Now execute it and It's done! 

    ./byfaces 


This works for me. Please let me know if It works for you. 

Ps. This will erase the files that were created by iPhoto but iPhoto will continue creating face files, so execute the script as you need it.

jueves, 3 de febrero de 2011

List to Tree (using whitespaces to indent) with Groovy

Supose you have a structure like this:













idnamefather
1N1null
11N111
12N121
121N12112
122N12212
13N131
131N13113
1311N1311131
13111N131111311
14N141
2N2null


public class Node {
def id
def name
def father
}

public class NodePrinter {
private void printLeftPad(def source,int pad)
{
for(int i=0;i<pad;i++) print " ";
println source;
}

public int indent(List items,int index,int pad)
{
printLeftPad("${items.get(index).name}",pad);

def current= items.get(index);
int i=index+1;
for(;i<items.size();i++)
{
if( items.get(i).father==current.id )
{
printLeftPad("{",pad);
i=indent(items,i,pad+4);
printLeftPad("}",pad);
}
else
{
if( current.father==items.get(i).father )
{
printLeftPad("${items.get(i).name}",pad);
current=items.get(i);
}
else
{
return i-1;
}
}
}

return i;
}

}

def nodes=[ new Node(id:1,name:'N1',father:null),
new Node(id:11,name:'N11',father:1),
new Node(id:12,name:'N12',father:1),
new Node(id:121,name:'N121',father:12),
new Node(id:122,name:'N122',father:12),
new Node(id:13,name:'N13',father:1),
new Node(id:131,name:'N131',father:13),
new Node(id:1311,name:'N1311',father:131),
new Node(id:13111,name:'N13111',father:1311),
new Node(id:14,name:'N14',father:1),
new Node(id:2,name:'N2',father:null)
];

def printer=new NodePrinter();
printer.indent(nodes,0,4);


This will give us the following result:

N1
{
N11
N12
{
N121
N122
}
N13
{
N131
{
N1311
{
N13111
}
}
}
N14
}
N2


Enjoy it!

martes, 20 de octubre de 2009

Source code formatter library for Java

Recently I was looking for a Java Library that could be include in an applet (with no any dependencies), after looking for awhile I could not find any library (there are a few out there but all of them have dependencies with other libraries). 

I found a C++ program named Artistic Style (http://astyle.sourceforge.net/) , so I decided to migrate the source code from C++ to Java, and the jastyle project arises (http://sourceforge.net/projects/jastyle/).

There are two ways in which jastyle could be used, as a library or as a console application. See how easy is to format Java source code with jastyle.

First, go to (http://sourceforge.net/projects/jastyle/) and download the lastest jastyle.jar , then choose the Java source file that you want to give format. The options will be shown if you just type:

java -jar jastyle.jar 

Now let's see how It works with an unformatted java source code:




package net.barenca.test;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.Random;

import oracle.jdbc.OracleDriver;

public class OracleBlobTest{
public static void main(String[] args) throws Exception
{
String filename="/home/barenca/Documents/LDAP.pdf";
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream inputStream = new BufferedInputStream(fis);

int length = inputStream.available();
DriverManager.registerDriver(new OracleDriver());
String url="jdbc:oracle:thin:@192.168.1.253:1521:devdb";
Connection conn = DriverManager.getConnection(url
, "prueba",
"prueba");
String insert = "insert into test_blob(id,content)values(?,?)";

PreparedStatement pst = conn.prepareStatement(insert);
int x = new Random(new Date().getTime()).nextInt(100000);

pst.setInt(1, x);
pst.setBinaryStream(2, inputStream, length);
pst.execute();
pst.close();

conn.close();
inputStream.close();
}}

And after java -jar jastyle.jar --style=java OracleBlobTest.java this is the result:



package net.barenca.test;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.Random;
import oracle.jdbc.OracleDriver;
public class OracleBlobTest {
public static void main(String[] args) throws Exception {
String filename ="/home/barenca/Documents/LDAP.pdf";
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream inputStream = new BufferedInputStream(fis);
int length = inputStream.available();
DriverManager.registerDriver(new OracleDriver());
String url ="jdbc:oracle:thin:@192.168.1.253:1521:devdb";
Connection conn = DriverManager.getConnection(url
, "prueba","prueba");
String insert = "insert into test_blob(id,content)values(?,?)";
PreparedStatement pst = conn.prepareStatement(insert);
int x = new Random(new Date().getTime()).nextInt(100000);
pst.setInt(1, x);
pst.setBinaryStream(2, inputStream, length);
pst.execute();
pst.close();
conn.close();
inputStream.close();
}
}

I think is not perfect, but It helps a lot :) .

Now, as a library :



import java.io.Reader;
import java.io.FileReader;
import java.io.BufferedReader;
import net.barenca.jastyle.ASFormatter;
import net.barenca.jastyle.FormatterHelper;

public static void main(String[] args) throws Exception
{

ASFormatter formatter = new ASFormatter();
formatter.setJavaStyle();
Reader in = new BufferedReader(new FileReader("OracleBlobTest.java"));

String formatted = FormatterHelper.format(in,formatter);

// and that's it!
}


The best thing is that this library does not need any additional jar library!!!.


I hope you enjoy it!.


Best regards.

Héctor.


jueves, 15 de octubre de 2009

Mapping Windows Key (Super) in Ubuntu

Probably one of the functions that a Windows user is accustom to is the mapping of the Windows key + E (this opens the Explorer -not the Internet Explorer), this combination of key mapping is not enabled by default in Ubuntu (I have tested it in Ubuntu 9.04, XUbuntu 8.10 and 9.04).

So, let me show you how easy is to map the windows key + E in order to have the same behavior in Ubuntu as Windows does it.

First go to option menu System -->Preferences-->Keyboard and then choose the tab "Layouts" and then "Layout options", and go to the Alt/Win key behavior subtree, open it and click on the radio button Supper key is mapped to Win keys and then click on close (or accept) and click on the another close button.




Second, go to System --> Preferences --> Keyboard Shortcuts and look for the Desktop section and click on the Home folder row, now press at the same time the two keys Windows + E (like in Windows - plus symbol should not be pressed), once you have done it, the combination of keys (the shortcut) to open Nautilus is ready!, accept the change.



Now continue mapping the keys you are accustom to. I hope this short description is useful for you.


Best regards.




lunes, 22 de junio de 2009

Error: No JDK found on PATH, Please correct the SetJavaHome directive or add the directive

If you have seen the following error while trying to execute Oracle SQL Developer:

Error: No JDK found on PATH
Please correct the SetJavaHome directive or add the directive
in /home/barenca/bin/sqldeveloper/sqldeveloper/bin/sqldeveloper.conf or
sqldeveloper-Linux.conf
to point to the JDK installation.

You just need to indicate the J2SDK path in the file sqldeveloper/bin/sqldeveloper.conf and that's it!.

Edit the file ./sqldeveloper/bin/sqldeveloper.conf and add the path of your j2sdk installation (in Linux/unix which java and then follow the symbolic links):

SetJavaHome /usr/lib/jvm/java-6-sun

And that's it!, enjoy it.

jueves, 18 de junio de 2009

Sound Volume keys in IceWM (tested with Latitude D620)

Some days ago I took sometime and I installed Antix 8, not everything is according with the features I was waiting for, but It is OK.

One thing It was missing was the configuration for the Sound Volume keys, so this is what I did for enabling the keys on my Laptop.

Go to the Antix Control Center, click on Edit IceWM settings, click on keys tab and append the following to the file:

key "XF86AudioLowerVolume" amixer -q set Master playback 5-

key "XF86AudioRaiseVolume" amixer -q set Master playback 5+

key "XF86AudioMute" amixer sset Master toggle

Then save the file.

Now click on the statup tab and append the following lines:

xmodmap -e 'keycode 176 = XF86AudioRaiseVolume'

xmodmap -e 'keycode 174 = XF86AudioLowerVolume'

xmodmap -e 'keycode 160 = XF86AudioMute'

Then save the file.

Close the session and It's done!.

martes, 23 de diciembre de 2008

Static IP on Xubuntu 8.10 (Intrepid Ibex)

1) Remove the network manager (this will remove the applet), go to the "install and Remove applications" available in the option menu System, find the Network Manager and remove.
2) Edit /etc/network/interfaces according to your needs. In my case my ethernet card is eth0 and my static IP will be 192.168.1.253

barenca@development:~$ sudo vi /etc/network/interfaces

auto lo eth0
iface lo inet loopback

iface eth0 inet static
address 192.168.1.253
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255

gateway 192.168.1.1

3) Add your DNS in the file /etc/resolv.conf

barenca@development:~$ sudo vi /etc/resolv.conf

# Generated by NetworkManager
nameserver 200.33.146.241
nameserver 200.33.146.249

4) Restart the service

barenca@development:~$ sudo /etc/init.d/networking restart

5) Test your connection. If no connection, do not worry, just restart and that's it!.

viernes, 5 de septiembre de 2008

Netbeans Visual Library and a Multiline Label Widget

Some days ago I was trying to find a solution for a multiline label widget for the netbeans visual library, I tried some solutions (out of the box) like QLabel and others found on the web, without any success, after 2 weeks of frustrating research, I decided to continue with other features of my system, and then later on, I returned to this issue again and give it a try.

The problem:
I needed a Widget that supported Multiline label, auto-fit on resize, and drag and drop action, the first approach was to include QLabel within a ComponentWidget, It did not work for me, and then, I tried with a JTextArea in this way:


public class MultilineLabelWidget
extends ComponentWidget
{
public MultilineLabelWidget( Scene scene, String text )
{
super( scene, new JTextArea( text ) );
JTextArea jText = (JTextArea) this.getComponent();
jText.setOpaque( false );
jText.setEditable( false );
jText.setLineWrap( true );
jText.setWrapStyleWord( true );
jText.setHighlighter( null );
jText.setBorder( BorderFactory.createEmptyBorder() );

this.getActions().addAction( ActionFactory.createResizeAction() );
this.getActions().addAction( ActionFactory.createMoveAction() );
this.setBorder( org.netbeans.api.visual.border.BorderFactory.createLineBorder( 8 ) );
}
}

and It partially worked!!, the problem is that JTextArea is painted after the widget, so the MoveAction will not work! out-of-the-box, ummm, I tried another solution, not extending the ComponentWidget but creating an in-line ComponentWidget and trying to catch the Mouse Events and redirect the calls to its Action in the Widget, like this:

JTextArea jText = new JTextArea( hm );
jText.setOpaque( false );
jText.setEditable( false );
jText.setLineWrap( true );
jText.setWrapStyleWord( true );
jText.setBorder( BorderFactory.createEmptyBorder() );
final ComponentWidget widget = new ComponentWidget(scene,jText);
widget.getActions().addAction( ActionFactory.createResizeAction() );
widget.getActions().addAction( ActionFactory.createMoveAction() );
jText.addMouseMotionListener( new MouseMotionListener(){

@Override
public void mouseDragged( MouseEvent event )
{
widget.getActions().mouseDragged( widget, new WidgetAction.WidgetMouseEvent(new Date().getTime(),event) );
}

@Override
public void mouseMoved( MouseEvent event )
{
widget.getActions().mouseMoved( widget, new WidgetAction.WidgetMouseEvent(new Date().getTime(),event) );
}} );

jText.addMouseListener( new MouseListener(){

@Override
public void mouseClicked( MouseEvent event )
{
widget.getActions().mouseClicked( widget, new WidgetAction.WidgetMouseEvent(new Date().getTime(),event) );
}

@Override
public void mouseEntered( MouseEvent event )
{
widget.getActions().mouseEntered( widget, new WidgetAction.WidgetMouseEvent(new Date().getTime(),event) );
}

@Override
public void mouseExited( MouseEvent event )
{
widget.getActions().mouseExited( widget, new WidgetAction.WidgetMouseEvent(new Date().getTime(),event) );
}

@Override
public void mousePressed( MouseEvent event )
{
widget.getActions().mousePressed( widget, new WidgetAction.WidgetMouseEvent(new Date().getTime(),event) );
}

@Override
public void mouseReleased( MouseEvent event )
{
widget.getActions().mouseReleased( widget, new WidgetAction.WidgetMouseEvent(new Date().getTime(),event) );
}} );
jText.setHighlighter( null );
widget.setBorder( org.netbeans.api.visual.border.BorderFactory.createLineBorder( 8 ) );

It worked better than the previous solution!, BUT!!!!!!!!!, It just worked when I moved the mouse pointer slowly (of course, first click and then drag), but every time I moved the mouse pointer as I usually do, the component was not repainted (It did not followed the mouse pointer), and at the moment I released the left button on the mouse, the widget was painted!, frustrating for me because I think It should be easy to do it! (please developer of Visual Library, include a Multiline Label Widget Out-of-the-box).

The solution
Finally, I found a code on the net (It references to com.exalto.UI) and adapted it to fit within the Visual Library Widget, so the result It is this:

package test.designer.widget;

import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;

import org.netbeans.api.visual.widget.LabelWidget;
import org.netbeans.api.visual.widget.Scene;

public class MultilineLabelWidget
extends LabelWidget
{
private boolean justify;

public MultilineLabelWidget( Scene scene, String label )
{
super( scene );
this.setLabel( label );
this.setJustified( true );
}

@Override
protected void paintWidget()
{
paintOrGetSize( this.getGraphics() );
}

private void paintOrGetSize( Graphics2D gr )
{
float width = (float) ( this.getBounds() != null ? this.getBounds().getWidth() : this.getPreferredSize()
.getWidth() );
Insets insets = this.getBorder().getInsets();
float rwidth = width - ( insets.left + insets.right );// + margin.left + margin.right;
Rectangle rec = this.calculateClientArea();
gr.setFont( getFont() );

float x = 0.0F;//+ margin.left;
float y = (float) rec.getY();//+ margin.top;

if ( rwidth > 0 && this.getLabel() != null && this.getLabel().length() > 0 )
{
AttributedString as = new AttributedString( this.getLabel() );
as.addAttribute( TextAttribute.FONT, getFont() );
AttributedCharacterIterator aci = as.getIterator();
LineBreakMeasurer lbm = new LineBreakMeasurer( aci, gr.getFontRenderContext() );

while ( lbm.getPosition() < aci.getEndIndex() )
{
TextLayout textLayout = lbm.nextLayout( rwidth );
if ( gr != null && isJustified() && textLayout.getVisibleAdvance() > 0.80 * rwidth )
{
textLayout = textLayout.getJustifiedLayout( rwidth );
}
if ( gr != null )
{
textLayout.draw( gr, x, y + textLayout.getAscent() );
}
y += textLayout.getDescent() + textLayout.getLeading() + textLayout.getAscent();

}
}
}

public boolean isJustified()
{
return justify;
}

public void setJustified( boolean justify )
{
boolean old = this.justify;
this.justify = justify;
if ( old != this.justify )
{
repaint();
}
}
}

It worked for me, It worked for my purposes, I hope It works for you.
Please modify it, improve the code, see if It works for you, and feedback to me.

Thanks a lot.

References:
http://graph.netbeans.org/servlets/ReadMsg?listName=users&msgNo=1295
http://graph.netbeans.org/servlets/ReadMsg?list=users&msgNo=726
http://www.koders.com/java/fid9BE9B31AC9BED01828448BF91A61AFA5AE431E16.aspx

miércoles, 3 de septiembre de 2008

Fast delete of files or directories in Linux using find

Let's suppose you have an structure like this:


mx.com.CVS
mx.com.dtc.ayde
mx.com.dtc.ayde.applet
mx.com.dtc.ayde.applet.CVS
mx.com.dtc.ayde.busquedas
mx.com.dtc.ayde.busquedas.CVS
mx.com.dtc.ayde.client


and you want to delete those directories with the name CVS, so, go to the root
directory of those you want to delete (in this case
/ ), and execute the following:


find . -type d -name CVS -exec rm -rf {} . \;

or

find . -type f -name *.db -exec cp {} . \;

for files that end with extension
db

the
. and \; are very important!


Regards,

Barenca

jueves, 14 de agosto de 2008

Remote time synchronization using NTP on CentOS

If you want to know how to configure the Network Time Protocol service on CentOS, here you have:


# chkconfig ntpd on

# ntpdate pool.ntp.org

# /etc/init.d/ntpd start



If you have not installed ntp, then before the previous lines install it with:

# yum install ntp


Best regards,

lunes, 7 de abril de 2008

Simple solution for the ORA-01157 and ORA-01110 Errors

Did you erase a datafile?, do you still need that datafile?, if the answer for the last question was yes, this is not the solution for you!, otherwise, continue...

SQL>startup mount;
SQL>alter database datafile '/AS10g/oradata/asdb/users02.dbf' offline drop;
SQL>alter database open;

SQL>shutdown immediate;
SQL>startup;


and then, you will see something like this:

Total System Global Area 1048576000 bytes
Fixed Size                   782524 bytes
Variable Size             892342084 bytes
Database Buffers          155189248 bytes
Redo Buffers                 262144 bytes



It is done!


In my case, I did not need that datafile anymore, so my problem was solved just following the above solution.

Regards,
Héctor Suárez Barenca

miércoles, 5 de marzo de 2008

Maximum subarray (java implementation)

You're given an array containing both positive and negative integers and required to find the subarray with the maximum sum.

This is an interesting problem, I read that the solution was given in 1977 in less than a minute, so I took the original algorithm for the article and I implemented with Java, enjoy it!

    public static void main(String[] args)
    {
        int[] offset = new int[2];
        int[] x = { 31, -41, 59, 26, -53, 58, 97, -93, -23, 18 };
        int n = x.length;
        int maxsofar = 0;
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
            {
                int sum = 0;
                for (int k = i; k <= j; k++)
                    sum += x[k];
                /* sum is sum of x[i..j] */
                if (sum > maxsofar)
                {
                    offset[0] = i;
                    offset[1] = j;
                    maxsofar = sum;
                }
            }
        System.out.println("Subarray [" + offset[0] + "..." + offset[1]
                + "] = " + maxsofar);
    }