memofy background

'vertz' memofied and shared items

vertz

How to change a text within <span> tag dynamically?

Created: 12.04.2010 14:29 Last Modified: 22.02.2011 23:03


How to change a text within <span> tag dynamically, like <span id="someid">text</text>

You have probably tried to do like this:

$('someid').value = 'some new text';

 

But it did not worked. The solution is to use innerHTML property, like:

$('someid').innerHTML = 'some new text';

 

 

Tags:    

vertz

Unable to instantiate Action: Spring, Struts 2 and Quartz

Created: 19.01.2010 00:00 Last Modified: 22.02.2011 22:51


Today we have received the following exception when added Quartz scheduler to spring framework application context.

Pretty strange as it looks like, right?

Unable to instantiate Action, actions.LoginAction, defined for 'login' in namespace '/'Failed to convert property value of type [java.util.LinkedHashMap] to required type [java.util.Map] for property 'fieldErrors'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.scheduling.quartz.SimpleTriggerBean] to required type [java.lang.String] for property 'fieldErrors[triggers][0]': no matching editors or conversion strategy found com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:307)

com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:388) com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:187) org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61) org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39) com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter.doFilter(StrutsExecuteFilter.java:88) com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129) com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter.doFilter(StrutsPrepareFilter.java:82)

The configuration for quartz schedullers were

 

<util:list id="triggers">
    <bean class="org.springframework.scheduling.quartz.SimpleTriggerBean">
      <property name="jobDetail">
        <bean ...>
      </property>
      <property name="repeatInterval" value="60000"/>
      <property name="volatility" value="false"/>
    </bean>
  </util:list>
  <bean name="local-schedule-factory" 
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers" ref="triggers"/>
    <property name="startupDelay" value="60"/>
  </bean>

 

Note, the list is declared as separate bean.

Was changed to:

 

<bean name="local-schedule-factory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
 autowire="no">
    <property name="triggers">
      <util:list id="triggers">
        <bean class="org.springframework.scheduling.quartz.SimpleTriggerBean" 
name="passwordRecoveryTriggerBean" autowire="no">
          <property name="jobDetail">
            <bean ...>
          </property>
          <property name="repeatInterval" value="60000"/>
          <property name="volatility" value="false"/>
        </bean>
      </util:list>
    </property>
    <property name="startupDelay" value="60"/>
  </bean>

 

And the problem was solved!

By sharing this we hope this could "save someone's a day" :-)

Tags:     

vertz

Accessing Android Resources By Name at Runtime

Created: 18.11.2010 01:35 Last Modified: 22.12.2010 21:14

Source: http://steven.bitsetters.com/2007/11/27/accessing-android-resources-by-name-at-runtime/


Accessing Android Resources By Name at Runtime

Use the getIdentifier method passing it the name of your resource, the resource type (id, raw) and your package name ( just use getPackageName())

int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());

After that you can use the id just like you would at compile time using the R class.

Tags:   

vertz

OutOfMemory exception when decoding with BitmapFactory

Created: 23.06.2010 00:00 Last Modified: 19.12.2010 11:27


 

When you try to decode large files on your Android device (where you have only 16MB memory available) you wil surely get an OutOfMemory exception.

We have found that if you create a temp storage and pass it to BitmapFactory before decoding might help.

So, before using BitmapFactory.decodeFile() create a byte array of 16kb and pass it to temp storage in decoding process.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];

Bitmap bitmapImage = BitmapFactory.decodeFile(path,opt);

Also you might consider passing your own outputstream that streams out to server or other storage to minimize memory consumtion during the process.

PS, do not forget to bitmapImage.recycle() after usage.

Also consider using options.inSampleSize with values other than 1. From SDK: If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. (1 -> decodes full size; 2 -> decodes 1/4th size; 4 -> decode 1/16th size). Because you rarely need to show and have full size bitmap images on your phone. For manipulations smaller sizes are usually enough.

 

 

Tags:   

vertz

How to compare month and year in dates (in Java)?

Created: 25.10.2010 22:16 Last Modified: 19.11.2010 00:07


Easy way to compare months and years for two dates

    final Calendar c = GregorianCalendar.getInstance();
    c.setTime(date);
    final Calendar c2 = GregorianCalendar.getInstance();
    c2.setTime(date2);
    return c.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c.get(Calendar.YEAR) == c2.get(Calendar.YEAR);

 

Tags:   

vertz

How to calculate months between two dates

Created: 25.10.2010 00:00 Last Modified: 19.11.2010 00:05


How to calculate months between two dates in Java? Simple question that took some time to solve.

  private String[] getMonthsAndYears(Date startDate, Date endDate) {
    final Calendar c = GregorianCalendar.getInstance();
    c.setTime(startDate);
    final Calendar c2 = GregorianCalendar.getInstance();
    c2.setTime(endDate);
    final int months = 
(c2.get(Calendar.YEAR) * 12 + c2.get(Calendar.MONTH))  - (c.get(Calendar.YEAR) * 12 + c.get(Calendar.MONTH));
    // first day of the month
    c.set(Calendar.DATE, 1);
    final String[] monthsAndDays = new String[months + 1];
    for (int i = 0; i < months; i++) {
      monthsAndDays[i] = new SimpleDateFormat("MM.yyyy").format(c.getTime());
      c.add(Calendar.MONTH, 1);
    }
    monthsAndDays[months] = new SimpleDateFormat("MM.yyyy").format(c.getTime()); // as last one 
    return monthsAndDays;
  }

Of course there are ready made solutions in frameworks like JODA time and others that help you to do just that. But sometimes you dont want to use those frameworks or have environments like android where you want to make your application be compact.

 

Tags:   

vertz

How to create a service that will run in the background in Android?

Created: 04.08.2010 23:09 Last Modified: 19.11.2010 00:03


How to create a service that will run in the background in Android?

This is done by creating a receiver and service classes.

Creating receiver and the service on Android is pretty easy.

First you have to register both, receiver and service in AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="...">
  <application android:icon="@drawable/icon" android:label="app">
    <activity ...
    <receiver android:name="PostingServiceReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
      </intent-filter>
    </receiver>
    <service android:name="PostingService"/>
  </application>

 

Next, create receiver like this (receiver is the one sho receives a message and does some action onReceive, in our case start the service):

public class PostingServiceReceiver extends BroadcastReceiver {
  public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
      context.startService(new Intent(context, PostingService.class));    
    }
  }
}

 

 

So this Receiver will get a broadcasted message BOOT_COMPLETED and will start the service as Intent

Service might look like this:

public class PostingService extends Service {
  private static final long POLL_INTERVAL = 60000; // every minute
  private Timer timer;
  @Override
  public void onCreate() {
    if (this.timer != null) {
      this.timer.cancel();
    }
    this.timer = new Timer();
    this.timer.schedule(new PostingServiceTimeTask(this), 5000, POLL_INTERVAL);
  }
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
  private class PostingServiceTimeTask extends TimerTask {
    private Service service;
    private PostingServiceTimeTask(Service service) {
      this.service = service;
    }

 

    public void run() {
    ....
    }
}

 

That means that run method will be called every minute (POLL_INTERVAL = 60000) to perform some work in the background.

Tags:   

vertz

How Do I Restart MySQL Server?

Created: 16.11.2010 15:47 Last Modified: 16.11.2010 15:48

Source: http://theos.in/desktop-linux/tip-that-matters/how-do-i-restart-mysql-server/


If you are using mysql on RedHat Linux (Fedora Core/Cent OS) then use following command:

 

* To start mysql server:

/etc/init.d/mysqld start

* To stop mysql server:

/etc/init.d/mysqld stop

* To restart mysql server

/etc/init.d/mysqld restart

Tip: Redhat Linux also supports service command, which can be use to start, restart, stop any service:

# service mysqld start
# service mysqld stop
# service mysqld restart


If you are using mysql on Debian / Ubuntu Linux then use following command:

 

* To start mysql server:

/etc/init.d/mysql start

* To stop mysql server:

/etc/init.d/mysql stop

* To restart mysql server

/etc/init.d/mysql restart

Dont forget to login as roor user first!!!

Tags:    

vertz

Java IO implementation of unix/linux “tail -f”

Created: 28.07.2010 00:00 Last Modified: 02.11.2010 13:34


Java implementation of Unix/Linux tail -f command

private class TailingStreamer extends Thread {
    boolean closed = false;
    private String filename;

    public TailingStreamer(String filename) throws IOException {
      this.filename = filename;
    }

    public void close() throws IOException {
      closed = true;
    }

    public void run() {
      FileInputStream is = null;
      try {
        is = new FileInputStream(filename);
        // read while closed flag is not raised
        while (true) {
          final int b = is.read();
          if (b != -1) {
            out.write(b);
          } else {
            if (closed) {
              break;
            }
            Thread.sleep(500); // sleep and wait
          }
        }
      } catch (Exception e) {
        // todo do something right?
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            //
          }
        }
      }
    }
  }

To use it just create and start the thread.

new TailingStreamer("path_to_file").start();

Use close method of TailingStreamer class to stop tailing.

Tags:   

vertz

Simple class to transfer data from one database to another

Created: 09.04.2010 22:50 Last Modified: 02.11.2010 13:34


Simple JAVA class to transfer data from one database to another (assumes that it has tables of the same type and structure)

import java.sql.*;

public class DataTransfer {
  private static String[] tableNames = new String[]{"SOME_TABLE_NAME"};
  private static final int FETCH_SIZE = 100;

  public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Connection sourceConnection = ...;
    Connection targetConnection = ...);

    // records transfered counter
    int c = 0;

    for (String tableName : tableNames) {
      final PreparedStatement ps = sourceConnection.prepareStatement("SELECT * FROM " + tableName);
      ps.setFetchSize(FETCH_SIZE);
      final ResultSet rs = ps.executeQuery();
      final ResultSetMetaData metaData = rs.getMetaData();
      final int columnCount = metaData.getColumnCount();
      String insertSQL = "INSERT INTO " + tableName + " ";

      while (rs.next()) {
        StringBuffer columns = new StringBuffer("(");
        StringBuffer params = new StringBuffer("(");

        for (int i = 0; i < columnCount; i++) {
          columns.append(metaData.getColumnName(i+1));
          params.append("?");
          if ((i+1) != columnCount) {
            columns.append(",");
            params.append(",");
          }
        }
        columns.append(")");
        params.append(")");

        final String sql = insertSQL + columns.toString() + " VALUES " + params.toString();

        c++;

        if (c >  0 && c % FETCH_SIZE == 0) {
          System.out.println("Transfered " + c + " records.");
        }

        final PreparedStatement insertStatement = targetConnection.prepareStatement(sql);
        for (int i = 0; i < columnCount; i++) {
          insertStatement.setObject(i+1, rs.getObject(i+1));
        }
        insertStatement.execute();
        targetConnection.commit();

        insertStatement.close();
      }
      rs.close();
      ps.close();
    }
    sourceConnection.close();
    targetConnection.close();
    System.out.println("Total transfered " + c + " records.");
  }
}

Tags:     

What Google have to add about that...