Monday, June 11, 2012

jquery datepicker localization persian , fa

<script type="text/javascript">

jQuery(function ($) {
    $.datepicker.regional['fa'] = {
        closeText:'بستن',
        prevText:'&#x3c;قبلي',
        nextText:'بعدي&#x3e;',
        currentText:'امروز',
        monthNames:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
        monthNamesShort:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
        dayNames:['يکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'],
        dayNamesShort:['يك', 'دو', 'سه', 'چه', 'پن', 'جم', 'شن'],
        dayNamesMin: ['ي', 'د', 'س', 'چ ', 'پ', 'ج ', 'ش'],
        weekHeader:'هف',
        dateFormat:'yy/mm/dd',
        firstDay:6,
        isRTL:true,
        showMonthAfterYear:false,
        yearSuffix:'',
        timeOnlyTitle: 'افقط زمان' ,
        timeText: 'زمان',
        hourText: 'ساعت',
        minuteText: 'دقيقه',
        secondText: 'ثانيه',
        ampm: false,
        month: 'ماه',
        week: 'هفته',
        day: 'روز',
        allDayText: 'همه روزها'
    };
    $.datepicker.setDefaults($.datepicker.regional['fa']);
});
</script>

Primefaces calendar localization persian , fa

<script type="text/javascript">

PrimeFaces.locales ['fa'] = {
    closeText:'بستن',
    prevText:'&#x3c;قبلي',
    nextText:'بعدي&#x3e;',
    currentText:'امروز',
    monthNames:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
    monthNamesShort:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
    dayNames:['يکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'],
    dayNamesShort:['يك', 'دو', 'سه', 'چه', 'پن', 'جم', 'شن'],
    dayNamesMin: ['ي', 'د', 'س', 'چ ', 'پ', 'ج ', 'ش'],
    weekHeader:'هف',
    dateFormat:'yy/mm/dd',
    firstDay:6,
    isRTL:true,
    showMonthAfterYear:false,
    yearSuffix:'',
    timeOnlyTitle: 'افقط زمان' ,
    timeText: 'زمان',
    hourText: 'ساعت',
    minuteText: 'دقيقه',
    secondText: 'ثانيه',
    ampm: false,
    month: 'ماه',
    week: 'هفته',
    day: 'روز',
    allDayText: 'همه روزها'
};

</script>

Sunday, May 27, 2012

Spring ACL based permission management

Key Concepts
Spring Security's domain object instance security capabilities center on the concept of an access control  list  (ACL). Every domain object instance in your system has its own ACL, and the ACL records details of  ho can and can't work with that domain object. With this in mind, Spring Security delivers three main  CL-related  capabilities to your application :
  • A way of efficiently retrieving ACL entries for all of your domain objects (and modifying those  CLs)
  •  A way of ensuring a given principal is permitted to work with your objects, before methods  re called
  •  A way of ensuring a given principal is permitted to work with your objects (or something they  return), after methods are called.
The tables are presented below in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last :
  • ACL_SID allows us to uniquely identify any principal or authority in the system ("SID" stands for "security identity"). The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a GrantedAuthority. Thus, there is a single row for each unique principal or GrantedAuthority. When used in the context of receiving a permission, a SID is generally called a "recipient".
  •  ACL_CLASS allows us to uniquely identify any domain object class in the system. The only columns are the ID and the Java class name. Thus, there is a single row for each unique Class we wish to store ACL permissions for.
  •  ACL_OBJECT_IDENTITY stores information for each unique domain object instance in the system. Columns include the ID, a foreign key to the ACL_CLASS table, a unique identifier so we know which ACL_CLASS instance we're providing information for, the parent, a foreign key to the ACL_SID table to represent the owner of the domain object instance, and whether we allow ACL entries to inherit from any parent ACL. We have a single row for every domain object instance we're storing ACL permissions for.
  •  Finally, ACL_ENTRY stores the individual permissions assigned to each recipient. Columns include a foreign key to the ACL_OBJECT_IDENTITY, the recipient (ie a foreign key to ACL_SID), whether we'll be auditing or not, and the integer bit mask that represents the actual permission being granted or denied. We have a single row for every recipient that receives a permission to work with a domain object.
Now that we've provided a basic overview of what the ACL system does, and what it looks like at a table structure, let's explore the key interfaces. The key interfaces are:
  • Acl: Every domain object has one and only one  Acl object, which internally holds the AccessControlEntrys as well as knows the owner of the Acl. An Acl does not refer directly to the domain object, but instead to an ObjectIdentity. The Acl is stored in the ACL_OBJECT_IDENTITY table.
  •  AccessControlEntry: An  Acl holds multiple  AccessControlEntrys, which are often abbreviated as ACEs in the framework. Each ACE refers to a specific tuple of Permission, Sid and Acl. An ACE an also be granting or non-granting and contain audit settings. The ACE is stored in the ACL_ENTRY table.
  •  Permission: A permission represents a particular immutable bit mask, and offers convenience functions for bit masking and outputting information. The basic permissions presented above (bits 0 through 4) are contained in the BasePermission class.
  •  Sid: The ACL module needs to refer to principals and  GrantedAuthority[]s. A level of indirection is provided by the Sid interface, which is an abbreviation of "security identity". Common classes include PrincipalSid (to represent the principal inside an Authentication object) and GrantedAuthoritySid. The security identity information is stored in the ACL_SID table.
  •  ObjectIdentity: Each domain object is represented internally within the ACL module by an ObjectIdentity. The default implementation is called ObjectIdentityImpl.
  •  AclService: Retrieves the  Acl applicable for a given  ObjectIdentity. In the included implementation (JdbcAclService), retrieval operations are delegated to a LookupStrategy. The LookupStrategy provides a highly optimized strategy for retrieving ACL information, using  atched retrievals (BasicLookupStrategy) and supporting custom implementations that leverage  aterialized views, hierarchical queries and similar performance-centric, non-ANSI SQL  apabilities.
  •  MutableAclService: Allows a modified Acl to be presented for persistence. It is not essential to  se this interface if you do not wish.
Getting Started :
To get starting using Spring Security's ACL capability, you will need to store your ACL information somewhere. This necessitates the instantiation of a DataSource using Spring. The DataSource is then injected into a JdbcMutableAclService and BasicLookupStrategy instance. The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. Refer to one of the samples that ship with Spring Security for an example configuration. You'll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements).
Once you've created the required schema and instantiated JdbcMutableAclService, you'll next need to ensure your domain model supports interoperability with the Spring Security ACL package. Hopefully ObjectIdentityImpl will prove sufficient, as it provides a large number of ways in which it can be used. Most people will have domain objects that contain a public Serializable getId() method. If the return type is long, or compatible with long (eg an int), you will find you  need not give further consideration to ObjectIdentity issues. Many parts of the ACL module rely on long identifiers. If you're not using long (or an int, byte etc), there is a very good chance you'll need to reimplement a number of classes. We do not intend to support non-long identifiers in Spring Security's ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios.
The following fragment of code shows how to create an Acl, or modify an existing Acl:

 // Prepare the information we'd like in our access control entry (ACE)
ObjectIdentity oi = new ObjectIdentityImpl(Foo.class, new Long(44));
Sid sid = new PrincipalSid("Samantha");
Permission p = BasePermission.ADMINISTRATION;
// Create or update the relevant ACL
MutableAcl acl = null;
try {
  acl = (MutableAcl) aclService.readAclById(oi);
} catch (NotFoundException nfe) {
  acl = aclService.createAcl(oi);
}
// Now grant some permissions via an access control entry (ACE)
acl.insertAce(acl.getEntries().length, p, sid, true);
aclService.updateAcl(acl);
 
In the example above, we're retrieving the ACL associated with the "Foo" domain object with identifier number 44. We're then adding an ACE so that a principal named "Samantha" can "administer" the object. The code fragment is  relatively self-explanatory, except the insertAce method. The first argument to the insertAce method is determining at what position in the Acl the new entry will be inserted. In the example above, we're just putting the new ACE at the end of the existing ACEs. The final argument is a boolean indicating whether the ACE is granting or denying. Most of the time it will be granting (true), but if it is denying (false), the permissions are effectively being blocked.
Spring Security does not provide any special integration to automatically create, update or delete ACLs as part of your DAO or repository operations. Instead, you will need to write code like shown above for your individual domain objects. It's worth considering using AOP on your services layer to automatically integrate the ACL information with your services layer operations. We've found this quite an effective approach in the past.
Once you've used the above techniques to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. You have a number of choices here. You could write your  own AccessDecisionVoter or AfterInvocationProvider that respectively fires before or after a method invocation. Such classes would use  AclService to retrieve the relevant ACL and then call  Acl.isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode) to decide whether permission is granted or denied. Alternately, you could use our  AclEntryVoter,  AclEntryAfterInvocationProvider or  AclEntryAfterInvocationCollectionFilteringProvider classes. All of  these classes provide a declarative-based approach to evaluating ACL information at runtime, freeing you from needing to write any code. Please refer to the sample applications to learn how to use these classes.

Exctracted from : Spring Security: Reference Documentation v3.1.0

MyBatis Insert

The Mapper interface method accepts the Object :

void insertAccount(Account account);

The Mapper xml uses the properties :

<insert id="insertAccount" parameterType="x.y.z.Account">

               INSERT INTO ACCOUNT (EMAIL, FIRSTNAME, LASTNAME, STATUS, ADDR1, ADDR2, CITY,
               STATE, ZIP, COUNTRY, PHONE, USERID)

VALUES

              (#{email}, #{firstName}, #{lastName}, #{status}, #{address1},  #{address2,jdbcType=VARCHAR}, 
              #{city}, #{state}, #{zip}, #{country}, #{phone}, #{username})

</insert>

Monday, May 14, 2012

I can't live, If living is without you !!!

Don't hesitate to download Ubuntu 12.4LTS

Http://www.ubuntu.com

Spring - Websphere - JNDI - JMS configuration

Define a JNDI template that other beans will be using for retrieving JNDI objects.
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.provider.url">smqp://localhost:4001/timeout=10000</prop>
<prop key="java.naming.factory.initial">com.swiftmq.jndi.InitialContextFactoryImpl</prop>
</props>
</property>
</bean>

Create a connection factory. I used Topic instead of Queue for my experiment.
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref ="jndiTemplate"/>
<property name="jndiName" value="TopicConnectionFactory"/>
</bean>
Create a Spring specific JMS template that will be used for sending JMS messages. Note that we are providing connection factory and a destination to the template. Destination is the message destination which is in our case named ‘testtopic’.
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestination" ref="destination"/>
<property name="pubSubDomain" value="true"/>
<property name="deliveryPersistent" value="true"/>
<property name="deliveryMode" value="2"/>
</bean>
<bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplate"/>
<property name="jndiName" value="testtopic"/>
</bean>
I create a MsgSender class and inject jmsTemplate and destination to it. This class simply sends a number of JMS messages to the provided destination using the template.
<bean id="sender" class="myexp.spring.MsgSender">
<property name="destination" ref="destination"/>
<property name="jmsTemplate" ref="jmsTemplate"/>
</bean>
After sending the messages, we need to receive it right? :) So here we are defining a Spring specific message listener container and providing a message listener to the container. For each message received, the onMessage method of the message listener will be called. In my experiment I simply printout the message in console.
<bean id="messageListener" class="myexp.spring.ExampleListener"/>
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="messageListener"/>
<property name="sessionAcknowledgeModeName" value="AUTO_ACKNOWLEDGE"/>
</bean>
My message sender is simple, it sends Text Messages a number of times, like this -

jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
String msgText = "Message " + messageIndex;
System.out.println("Publishing - " + msgText);
Message message = session.createTextMessage(msgText);
message.setLongProperty("startTime", System.currentTimeMillis());
return message;
}
});

I an addition to a String message, I am also adding additional property into the message. The listener class must implement javax.jms.MessageListener and implement the following method -

public void onMessage(Message message) {
TextMessage msg = (TextMessage) message;
System.out.println("Reading - " + msg.getText());
}

see :

Wednesday, May 9, 2012

How t send multiple parameters to mybatis xml mapper file?

Problem

Using a single parameter is very easy. The example on page 30 of the user guide shows this (see below). But How do we use multiple parameters?
UserMapper.xml:
<select id=”selectUser” parameterType=”int” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where id = #{id}</sql>
UserMapper.java:
public interface UserMapper{
  User selectUser(int id);
}

Solution

  1. Add the @Param("name") to your Mapper.java
  2. Change the parameterType in Mapper.xml to "map"

1. Add the @Param("name") to your Mapper.java

UserMapper.java:
import org.apache.ibatis.annotations.Param;
public interface UserMapper{
   User selectUser(@Param("username") String usrename, 
                   @Param("hashedPassword") String hashedPassword);
}

2. Change the parameterType in Mapper.xml to "map"

UserMapper.xml:
<select id=”selectUser” parameterType=”map” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where username = #{username}
  and hashedPassword = #{hashedPassword}</sql>
 
 
see :
http://code.google.com/p/mybatis/wiki/HowToSelectMultipleParams 

Saturday, April 21, 2012

Configuring the WebSphere node agent to run as a Windows service

  1. Change to the \bin directory where WebSphere is installed, for example:
       C:\Program Files\IBM\WebSphere\AppServer\bin
  2. Run the following command:
      wasservice -add ctgNode01_nodeagent 
        -servername nodeagent 
        -profilePath "...\IBM\WebSphere\AppServer\profiles\ctgAppSrv01" 
        -wasHome "...\IBM\WebSphere\AppServer" 
        -logFile "...\IBM\WebSphere\AppServer\profiles\ctgAppSrv01\logs\nodeagent\startNode.log" 
        -logRoot "...\IBM\WebSphere\AppServer\ctgAppSrv01\logs\nodeagent" 
        -restart true 
        -startType automatic
  3. Use a registry editor, such as Regedit, and open this key:
      HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\IBMWAS61Service - ctgCellManager01
  4. Create a Multi-String Value named DependOnService.
  5. Enter the value "IBMWAS61Service - ctgNode01_nodeagent" for this new key. This will make the WAS Cell Manager service dependant on the node agent service starting first.

see : http://publib.boulder.ibm.com/infocenter/tivihelp/v10r1/index.jsp?topic=%2Fcom.ibm.srm.doc_7.1%2Finstalling%2Fsrc%2Ft_ccmdb_confignodeagentrtorunasservice.html

Thursday, September 8, 2011

JCopia

Have you ever thought how to download video and audio from flash players on internet sites like Youtube, Google Video, MySpace, DailyMotion, Metacafe, Break, Blog sites of your friends with embedded audio and video content and so on?

This is a commercial product :


Capture flash video and audio from any website to your computer

Tuesday, July 12, 2011

maven copy Dependenies/Resources

Add the following plugin to your pom to copy dependencies :
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${deployment.dir}</outputDirectory>                                      
                            <excludeArtifactIds>javaee-api</excludeArtifactIds>
                        </configuration>   
                    </execution>
                   
                </executions>
            </plugin>

 Add the following plugin to your pom to copy Resources :

            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.5</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${deployment.dir}</outputDirectory>
                            <resources>         
                                <resource>
                                    <directory>target</directory>
                                    <filtering>true</filtering>
                                    <includes>
                                        <include>*.jar</include>
                                    </includes>
                                </resource>
                            </resources>             
                        </configuration>           
                    </execution>
                </executions>
            </plugin>
 
You can then simply run the Project and have the needed libraries in your deployment location.

But remember to define the properties for addressing the target library. In this example :


    <properties>
        <glassfish.home>/opt/programs/glassfish</glassfish.home>
        <deployment.dir>${glassfish.home}/glassfish/domains/my-domain/lib</deployment.dir>
    </properties>

my maven assembly plugin

I want the provided dependencies in the current project and all the included submodules to take place in the current project's target/lib-lib directory.

the assembly.xml file :


<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xsi:schemalocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>assembly</id>
<formats>
<format>dir</format>
</formats>

<modulesets>
<moduleset>


<useallreactorprojects>true</useallreactorprojects>


<includes>


<include>CHILD-MODULE-1-GROUP-ID:
CHILD-MODULE-1-ARTIFACT-ID</include>
<include>CHILD-MODULE-2-GROUP-ID:CHILD-MODULE-2-ARTIFACT-ID</include>
</includes>

<binaries>
<dependencysets>
<dependencyset>
<outputdirectory>/lib-lib</outputdirectory>

<unpack>false</unpack>
<scope>provided</scope>
</dependencyset>
</dependencysets>
<includedependencies>true</includedependencies>
</binaries>
</moduleset>
</modulesets>

</assembly>


the pom.xml file :

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.1</version>
                <configuration>
                    <descriptors>
                        <descriptor>assembly.xml</descriptor>
                    </descriptors>
                </configuration>
            </plugin>
        </plugins>
    </build>

Now use the "package assembly:assembly" action to execute it.

Tuesday, May 3, 2011

find unwanted charsets and collations in your mysql schemas

Use this command to find the unwanted charachter set and collations :

# note that the unwanted collation in this sample is 'utf8_persian_ci', and the
# correct collation is to be 'utf8_general_ci'


SELECT table_schema, table_name, column_name, character_set_name, collation_name
FROM information_schema.columns
WHERE collation_name = 'utf8_persian_ci'
and character_set_name = 'utf8'
and table_schema = 'smartbase'
ORDER BY table_schema, table_name,ordinal_position;


then use the follownig script to correct them :


ALTER TABLE THE_TABLE_NAME CONVERT TO CHARACTER SET utf8 COLLATE 'utf8_general_ci';

Thursday, February 24, 2011

Manupulate Environment Variables using Terminal - ubuntu

see :
https://help.ubuntu.com/community/EnvironmentVariables

Friday, October 1, 2010

How to mount NTFS drives in ubuntu

you have to get the  ntfs-config to fo that , run in the terminal :

sudo apt-get install ntfs-config

Then go to System --> Administration --> NTFS Configuration Tool

There you will see a list of your NTFS drives. Check wichever you would like to mount and have them mounted .

Thats easy

Thursday, September 9, 2010

how to reset mysql password

If you know the root password, but want to change it, see Section 12.4.1.6, “SET PASSWORD Syntax”.
If you set a root password previously, but have forgotten it, you can set a new password. The following sections provide instructions for Windows and Unix systems, as well as generic instructions that apply to any system.
B.5.4.1.1. Resetting the Root Password: Windows Systems
On Windows, use the following procedure to reset the password for all MySQL root accounts:
  1. Log on to your system as Administrator.
  2. Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list and stop it.
    If your server is not running as a service, you may need to use the Task Manager to force it to stop.
  3. Create a text file containing the following statements. Replace the password with the password that you want to use.

    UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
    FLUSH PRIVILEGES;
    Write the UPDATE and FLUSH statements each on a single line. The UPDATE statement resets the password for all root accounts, and the FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.
  4. Save the file. For this example, the file will be named C:\mysql-init.txt.
  5. Open a console window to get to the command prompt: From the Start menu, select Run, then enter cmd as the command to be run.
  6. Start the MySQL server with the special --init-file option (notice that the backslash in the option value is doubled):

    C:\> C:\mysql\bin\mysqld --init-file=C:\\mysql-init.txt
    If you installed MySQL to a location other than C:\mysql, adjust the command accordingly.
    The server executes the contents of the file named by the --init-file option at startup, changing each root account password.
    You can also add the --console option to the command if you want server output to appear in the console window rather than in a log file.
    If you installed MySQL using the MySQL Installation Wizard, you may need to specify a --defaults-file option:

    C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld.exe"
             --defaults-file="C:\\Program Files\\MySQL\\MySQL Server 5.1\\my.ini"
             --init-file=C:\\mysql-init.txt
    The appropriate --defaults-file setting can be found using the Services Manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list, right-click it, and choose the Properties option. The Path to executable field contains the --defaults-file setting.
  7. After the server has started successfully, delete C:\mysql-init.txt.
You should now be able to connect to the MySQL server as root using the new password. Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.

see :
http://dev.mysql.com/doc/refman/5.1/en/resetting-permissions.html#resetting-permissions-windows

Tuesday, August 31, 2010

How to parse a PDF

PDFBox is a Java API from Ben Litchfield that will let you access the contents of a PDF document. It comes with integration classes for Lucene to translate a PDF into a Lucene document.
 
JPedal is a Java API for extracting text and images from PDF documents.
 
PDFTextStream is a Java API for extracting text, metadata, and form data from PDF documents. It also comes with an integration module making it easier to convert a PDF document into a Lucene document.
 
XPDF is an open source tool that is licensed under the GPL. It's not a Java tool, but there is a utility called pdftotext that can translate PDF files into text files on most platforms from the command line.
 
Based on xpdf, there is a utility called pdftohtml that can translate PDF files into HTML files. This is also not a Java application.

How to change the encoding of a java String

String newStr = new String(someString.getBytes("UTF-8"));

Monday, August 30, 2010

JAVA -- write a java.sql.blob to File

public void saveToFile(Blob blob) {
                try {
                    File file = new File("c:/someFileName.ext");
                    FileOutputStream os = new FileOutputStream(file);
                    os.write(getBlobBytes(blob));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "Error!");
                }
}



public byte[] getBlobBytes(Blob blob) throws Exception {
        final int MAXBUFSIZE = 4096;
        if (blob != null) {
            try {
                BufferedInputStream bis = new BufferedInputStream(blob
                        .getBinaryStream());
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                byte[] buf = new byte[MAXBUFSIZE];
                int n = 0;
                while ((n = bis.read(buf, 0, MAXBUFSIZE)) != -1) {
                    bo.write(buf, 0, n);
                }
                bo.flush();
                bo.close();
                bis.close();
                buf = null;
                return bo.toByteArray();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

JDBC -- Inserting binary data

Inserting Data :

    public void saveMedia(File file, short type) {
        FileInputStream io=null;
        try{
            io = new FileInputStream(file);
        }catch(IOException ioEx){
            ioEx.printStackTrace();
        }
        try {
            PreparedStatement statement = connection.prepareStatement("insert into media (content,mediatype,fileName) values(?,?,?)");
            statement.setBinaryStream(1, io, file.length());
            statement.setShort(2, type);
            statement.setString(3,file.getName());
            statement.executeUpdate();
            connection.close();
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        } catch(ClassNotFoundException cnfEx){
            cnfEx.printStackTrace();
        }
    }

Monday, August 23, 2010

Important matter in indexing --> Solr

Data sent to Solr is not immediately searchable, nor do deletions take immediate
effect. Like a database, changes must be committed frst. Unlike a database, there
are no distinct sessions (that is transactions) between each client, and instead there
is in-effect one global modifcation state. This means that if more than one Solr client
were to submit modifcations and commit them at similar times, it is possible for part
of one client's set of changes to be committed before that client told Solr to commit.
Usually, you will have just one process responsible for updating Solr. But if not, then
keep this in mind.

From :
Solr 1.4 Enterprise Search Server (Packt, 2009, 1847195881) 

index-time-boosting while posting an xml to solr

Here is a sample XML fle you can HTTP POST to Solr:

<add allowDups="false">
<doc boost="2.0">
<field name="id">5432a</field>
<field name="type" ...</field>
<field name="a_name" boost="0.5"></field>
<!-- the date/time syntax MUST look just like this (ISO-8601)-->
<field name="begin_date">2007-12-31T09:40:00Z</field>
</doc>
<doc>
<doc>
<field name="id">5432a</field>
<field name="type" ...
<field name="begin_date">2007-12-31T09:40:00Z</field>
</doc>
<!-- more here as needed -->
</add>


The allowDups defaults to false to guarantee the uniqueness of values in the feld
that you have designated as the unique feld in the schema (assuming you have such
a feld). If you were to add another document that has the same value for the unique
feld, then this document would override the previous document, whether it is
pending a commit or it's already committed. You will not get an error.
If you are sure that you will be adding a document that is not
a duplicate, then you can set allowDups to true to get a
performance improvement.

Boosting affects the scores of matching documents in order to affect ranking in 
score-sorted search results. Providing a boost value, whether at the document or
feld level, is optional. The default value is 1.0, which is effectively a non-boost.
Technically, documents are not boosted, only felds are. The effective boost value 
of a feld is that specifed for the document multiplied by that specifed for the feld.

Specifying boosts here is called index-time boosting, which is rarely
done as compared to the more fexible query-time boosting. Index-time
boosting is less fexible because such boosting decisions must be decided
at index-time and will apply to all of the queries.



From :
Solr 1.4 Enterprise Search Server (Packt, 2009, 1847195881)

Friday, August 20, 2010

The OSGi Architecture

The OSGi technology is a set of specifications that define a dynamic component system for Java. These specifications enable a development model where applications are (dynamically) composed of many different (reusable) components. The OSGi specifications enable components to hide their implementations from other components while communicating through services, which are objects that are specifically shared between components. This surprisingly simple model has far reaching effects for almost any aspect of the software development process.

Though components have been on the horizon for a long time, so far they failed to make good on their promises. OSGi is the first technology that actually succeeded with a component system that is solving many real problems in software development. Adopters of OSGi technology see significantly reduced complexity in almost all aspects of development. Code is easier to write and test, reuse is increased, build systems become significantly simpler, deployment is more manageable, bugs are detected early, and the runtime provides an enormous insight into what is running. Most important, it works as is testified by the wide adoption and use in popular applications like Eclipse and Spring. 

see :
http://www.osgi.org/About/WhatIsOSGi

Thursday, August 19, 2010

How to deploy Solr on Tomcat

  • Step 2 : Make a folder somewhere in your computer and name it 'solr_home' (it can have any name). I assume that you have made a folder with the path : C:\ solr-home.
  • Step 3 : Copy the following folders to you solr-home directory which you made in the last step. 
    1. apache-solr-x.x.x/example/lib
    2. apache-solr-x.x.x/example/solr/conf
    3. apache-solr-x.x.x/example/solr/bin
  • Step 4 : Copy the war file placed in the ./apache-solr-x.x.x/dist folder which has a name like apache-solr-x.x.x.war (where x.x.x is the version of your solr core) and paste it in your tomcat webapps directory. 
  • Step 5 : Rename the file 'solr-x.x.x.war'  to solr.zip.
  • Step 6 : Now you have to set the Solr home page in order to tell tomcat where to save your indexes.  The first way to approach this aim is to open the web.xml file in Notepad located in the Solr.zip/WEB-INF directory. Find the <env-entry> element (it should be commented by default). Copy it whole and paste it to the bottom of your xml doc. something like :
<env-entry>
<env-entry-name>solr/home</env-entry-name>
<env-entry-value>C:\ solr-home</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry> .
Also you can set the solr home directory in tomcat configuration panel. To do that , right-click on the icon of tomcat in the notification area , select configure,  go to the  java tab, add the following line to the java options :
-Dsolr.solrhome=C:\solr-home

Friday, August 13, 2010

Java Message Service API (the JMS API)

General idea of messaging

Messaging is a form of loosely coupled distributed communication, where in this context the term 'communication' can be understood as an exchange of messages between software components. Message-oriented technologies attempt to relax tightly coupled communication (such as TCP network sockets, CORBA or RMI) by the introduction of an intermediary component, which in this case would be a queue. The latter approach allows software components to communicate 'indirectly' with each other. Benefits of this include message senders not needing to have precise knowledge of their receivers, since communication is performed using this queue. This is the first of two types: point to point and publish and subscribe.

Java Message Service API Overview

The Java Message Service (JMS) defines the standard for reliable Enterprise Messaging. Enterprise messaging, often also referred to as Messaging Oriented Middleware (MOM), is universally recognized as an essential tool for building enterprise applications. By combining Java technology with enterprise messaging, the JMS API provides a powerful tool for solving enterprise computing problems.

Enterprise messaging provides a reliable, flexible service for the asynchronous exchange of critical business data and events throughout an enterprise. The JMS API adds to this a common API and provider framework that enables the development of portable, message based applications in the Java programming language.

The JMS API improves programmer productivity by defining a common set of messaging concepts and programming strategies that will be supported by all JMS technology-compliant messaging systems.

The JMS API is an integral part of the Java 2, Enterprise Edition (J2EE) platform, and application developers can use messaging with components using J2EE APIs ("J2EE components").

Version 1.1 of the JMS API in the J2EE 1.4 platform has the following features:
  • Message-driven beans enable the asynchronous consumption of JMS messages.
  • Message sends and receives can participate in Java Transaction API (JTA) transactions.
  • J2EE Connector Architecture interfaces that allow JMS implementations from different vendors to be externally plugged into a J2EE 1.4 application server.
The addition of the JMS API enhances the J2EE platform by simplifying enterprise development, allowing loosely coupled, reliable, asynchronous interactions among J2EE components and legacy systems capable of messaging. As a developer, you can easily add new behavior to a J2EE application with existing business events by adding a new message-driven bean to operate on specific business events.

The J2EE platform's Enterprise JavaBeans (EJB) container architecture, moreover, enhances the JMS API in two ways:
  • By allowing for the concurrent consumption of messages
  • By providing support for distributed transactions, so that database updates, message processing, and connections to EIS systems using the J2EE Connector Architecture can all participate in the same transaction context.

See : 
http://www.oracle.com/technetwork/java/overview-137943.html

See also: Message-oriented middleware and Message passing

And a complete useful tutorial you cant miss :
http://download-llnw.oracle.com/javaee/1.3/jms/tutorial/1_3_1-fcs/doc/overview.html 

The Java Management Extensions (JMX) API

The JMX API is a standard API for management and monitoring of resources such as applications, devices, services, and the Java virtual machine.
Typical uses of the JMX technology include:
  • Consulting and changing application configuration.
  • Accumulating and publishing statistics about application behavior.
  • Notifying users or applications of state changes and erroneous conditions.
The JMX API includes remote access, so a remote management program can interact with a running application for the above purposes.

see :
http://openjdk.java.net/groups/jmx/
http://en.wikipedia.org/wiki/Java_Management_Extensions

tutorial for starting Spring Roo

This is where you can find a very good tutorial for Spring Roo version 1.0.2 , creating a Roo based project from the scratch :

http://www.lalitbhatt.com/tiki-index.php?page=Spring+Roo

Tuesday, August 10, 2010

how to prevent lack of memory while executing large jasper reports

        JRSwapFile swapFile =
                    new JRSwapFile(getServletContext().getRealPath("/report/swap/"), 1024 * 50/* 50 KB */, 2);
        virtualizer = new JRSwapFileVirtualizer(40, swapFile);
        virtualizer.setReadOnly(false);
        reportParam_.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);

Monday, August 9, 2010

Software versioning

Software versioning is the process of assigning either unique version names or unique version numbers to unique states of computer software. Within a given version number category (major, minor), these numbers are generally assigned in increasing order and correspond to new developments in the software.

see :
http://en.wikipedia.org/wiki/Software_versioning