Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Wednesday, May 5, 2021

Handling Exceptions in EJB using Interceptors

In my previous posts Using EJB Interceptors to add functionality to existing Beans, and Using EJB Interceptors to execute code AFTER service method completes, we saw how to use EJB3 Interceptors to add common concern features like logging, etc. to J2EE service methods.
In case you want to have common exception handling logic for all service method calls, you can wrap the return context.proceed(); in a try-catch block and handle the exception in the catch block as shown below:


package com.my.ejb.interceptors;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class MyInterceptor {

    @AroundInvoke
    public Object interceptorMethod(InvocationContext context) throws Exception {
    	try {
          System.out.println("Before invoking method: " + context.getMethod());
          return context.proceed();
        } catch (Exception e) { // You can catch ALL or ONLY Specific Exceptions as per your requirement
          System.out.println("Exception in method " + context.getMethod() + ": " + e.getMessage());
        } finally {
          System.out.println("After invoking method: " + context.getMethod());
        }
    }
}

Once this interceptor is created, we just need to add an "@Interceptors" annotation to the target EJB as:

import javax.interceptor.Interceptors;

@Interceptors({com.my.ejb.interceptors.MyInterceptor.class})

Now you should see log lines "Before ..." before the the method executes and "After..." after the method executes and in case of any exceptions in the metod call, you will see "Exception ..."


Tuesday, May 4, 2021

Using EJB Interceptors to execute code AFTER service method completes

In my previous post Using EJB Interceptors to add functionality to existing Beans, we saw how to use EJB3 Interceptors to add common concern features like logging, etc. to J2EE service methods.
In case you want to run any piece of code after each service method call, you can wrap the return context.proceed(); in a try-finally block and add the "after" code in the finally block as shown below:


package com.my.ejb.interceptors;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class MyInterceptor {

    @AroundInvoke
    public Object interceptorMethod(InvocationContext context) throws Exception {
    	try {
          System.out.println("Before invoking method: " + context.getMethod());
          return context.proceed();
        } finally {
          System.out.println("After invoking method: " + context.getMethod());
        }
    }
}

Once this interceptor is created, we just need to add an "@Interceptors" annotation to the target EJB as:

import javax.interceptor.Interceptors;

@Interceptors({com.my.ejb.interceptors.MyInterceptor.class})

Now you should see log lines "Before ..." before the the method executes and "After..." after the method executes!


Tuesday, November 10, 2020

Using EJB Interceptors to add functionality to existing Beans

To add any decorations or cross-cutting features like logging, profiling or performance measurement for service method calls of existing enterprise beans, you can use EJB3 Interceptors that were provided starting with JavaEE5.

Interceptor is a method that wraps around the invocation of the actual business method call allowing you to apply the required feature and can either exist in the target class if it is very speficic to that class; or in an external class if it applies to multiple service methods. If it is a part of an external class, then it has to be the only method in that class having the annotation "@AroundInvoke"

This interceptor method takes the following form:

package com.my.ejb.interceptors;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class MyInterceptor {

    @AroundInvoke
    public Object interceptorMethod(InvocationContext context) throws Exception {
        System.out.println("Going to invoke method: " + context.getMethod());
        return context.proceed();
    }
}

Once this interceptor is created, we just need to add an "@Interceptors" annotation to the target EJB as:

@Interceptors({com.my.ejb.interceptors.MyInterceptor.class})
And viola - it simply works, no need for any additionaly libraries or frameworks!

Note: Do not forget the return context.proceed(); call at the end of the interceptor method - this will allow the chain of interceptors to proceed and the target metod to be invoked!

Saturday, April 12, 2014

Throttle task submission in Java - Simple solution

JDK provides a convenient java.util.concurrent.Executors factory with useful methods to return various java.util.concurrent.Executor implementation instance pre-configured with commonly used settings. However, there is no implementation or configuration available for an implementation that throttles task submission. Here I provide my take on a very simple solution for this requirement.

private void submitTasks(List tasksList) {
  final ThreadPoolExecutor executor = new ThreadPoolExecutor(MIN_POOL_SIZE,
                                                             MAX_POOL_SIZE,
                                                             60L,
                                                             TimeUnit.SECONDS,
                                                             new LinkedBlockingQueue());
  for (Runnable task : tasksList) {
    while (executor.getQueue().size() > MAX_Q_SIZE) {
      // Throttle for WAIT_FOR_SECONDS seconds if queue is full
      try {
        log.info("Waiting " + WAIT_FOR_SECONDS + " seconds as Queue size is: " + executor.getQueue().size());
        Thread.sleep(WAIT_FOR_SECONDS * 1000);
      } catch (InterruptedException e) {
        // Ignore
      }
    }
    executor.execute(task);
  }
  // inform the executor there are no more tasks
  executor.shutdown();
}

Instead of using the factory to get a pre-configured executor, I create my own ThreadPoolExecutor using a LinkedBlockingQueue. This allows us access to the underlying queue for the throttling feature. Before submitting the task, I check if the current queue size is greater than a certain size and if so, then wait for a configured time repeatedly till the queue is smaller.
This implementation is very useful for the scenarios where you have lots of short running tasks that need to be processed by a fixed small number of threads.

Tuesday, July 23, 2013

Split String into Fixed Length chunks using Java

I needed to split a large string into fixed length chunks of equal size using Java Apart from the regular method of looping and doing a substring for the required length, I was wondering in what other way was it possible to achieve the same. Of course, it's Mr. Regex to the rescue for this task at hand! Here was the regex I used to do this:
String largeString = "This is a very large and totally useless and meaningless string";
int chunkLength = 5;
String[] chunks = largeString.split("(?<=\\G.{" + chunkLength + "})");
System.out.println("Number of chunks: " + chunks.length); // Should print 13
System.out.println("Chunk size: " + chunks[0].size()); // Should print 5 == chunkLength
The regular expression is a Positive Look-Behind looking for any chunkLength characters beginning at the position where the last match ended. So the first time around, it matches the beginning of the string and then after that, it keeps matching every set of chunkLength characters.
This makes me think I should write a more detailed post about regular expressions, especially on Look-Ahead and Look-Behind - stay tuned!

Tuesday, April 30, 2013

Viewing scrolled out logger lines in Eclipse console

Some programs output a lot of text onto the console in Eclipse, especially in debug mode. To ensure that all console output for such programs is available, here are a few Eclipse settings that will be very helpful. Go to Window > Preferences > Run/Debug > Console and change the following:
  1. Fixed width console: un-check this property
  2. Limit console output: un-check this property
  3. Displayed tab width: set this to 4
Save these changes and run the program again. Now you can see the specific logger lines that you want to monitor even if they scroll by and go out of the console.

Thursday, April 18, 2013

Java 5 - Summary of new & important features

Here is a summary of the useful features that were introduced in Java 5.

Generics simplify code
Adds compile-time type safety and eliminates the necessity for type casting without any performance hit

Enhanced For loops - also known as For/Each
Simplifies looping code but does not make the iterator visible. Loops through each entry of the collection/array returning one properly cast value at a time for processing - without requiring to define an Iterator.

Typesafe Enums
Better than public static final String variables - allows us to create enumerated types with arbitrary methods and fields

Metadata Annotations
Reduces coding issues like overloading instead of overriding with the use of pre-defined annotations. Allows
for a more declarative style of programming reducing boiler-plate code with user-defined annotations.

Varargs provides flexibility
Methods can accept a multiple number of parameters defined at runtime with a few restrictions - they have to be the last set of parameters of the method and all have to be of the same data type. The ellipsis "…" is used to indicate that the argument might appear a variable number of times.

Auto Boxing / Unboxing
Implicit conversion between primitives and their wrapper classes - convenient, but can have lower performance as primitives are stored on the stack while the actual objects are stored in the heap.

Synchronization changes in java.util.concurrent package
Introduction of Locks concept to provide better semantics than "synchronized" keyword and many more useful features like Read/Write locks.

Static import
Makes code more readable and reduces redundant typing for qualifying the static members (methods & fields) of a class with the class name in each occurance

Performance improvements with better GC, StringBuilder, etc

Formatter allows for better printing with printf
No more clumsy println's with string concatenation - use C-style printf with format strings.

Scanner simplifies basic parsing
Easier than String.split and Integer.parseInt

These are too numerous and important to detail all of them in a single post - so each will be covered in detail with code examples in posts of their own soon.


Check out the Summary of Java 7 features that make Java even better!

Friday, September 16, 2011

Good day for Developers

It seems that today is a very good day for Developers!
On one hand, Google, launched its APIs for the Google+ platform here.
On the other, Windows is offering a free download of its' latest Win8 build here.
Hmmm ... decision, decisions, time crunch!

Tuesday, September 13, 2011

Happy Programmers' Day!

Today is 13th September - the 256th day of the year. The number 256 holds a special place in the eyes of (most) programmers as it is the highest value that can be represented with a byte: 2^8 or 0b11111111. Since this is the highest integer less than 365 (days in a year) that can be represented with powers of 2, this is celebrated as Programmers' Day. Read more on the history of Programmers' Day at Wikipedia.
Sadly - Google does not have any Doodles for this on their home page even though they are a very techie company.

Tuesday, August 2, 2011

Java 7 Summary of New Features

Here is a summary of the new features released in Java 7 as part of Project Coin language enhancements are:
  1. Improved Numeric Literals - Binary integral literals and Underscore in numeric literals
  2. Strings in switch
  3. Diamond operator or simpler type inference for generic instance creation
  4. try-with resource statement
  5. Multi-catch and more precise throw
  6. Simplified varargs method invocation
  7. Fork & Join enhancements
  8. NIO 2.0 & File system access enhancements
These are explained in detail below.

Improved Numeric Literals
Integral types (byte, short, int, and long) can also be expressed using the binary number system by prefixing "0b" or "0B" to the number's binary representation as:
int binaryLiteral = 0b110011

You can have underscores in numeric literals to make them more readable like:
int tenMillion = 10_000_000;

Strings in switch
Till Java6, only numbers or enums could be used in switch statements. Now strings are also allowed:
String switchString = getStringValue();
switch(switchString) {
    case "foo": doFoo();
                break;
    case "bar": doBar();
                break;
    case "fuu": doFuu();
                break;
    default: doDefault();
             break;
}
Diamond operator
This is a short cut to reduce typing and make it simpler to infer generic types during instance creation
Map<String, List<Pair<String,BigDecimal>> myMap = new HashMap<>();

Simplified varargs method invocation
When a programmer tries to invoke a *varargs* (variable arity) method with a non-reifiable varargs type, the compiler currently generates an "unsafe operation" warning. This proposal moves the warning from the call site to the method declaration. This merits more detailed explanation and a separate post.

Multi-catch and more precise throw
Now you can catch multiple exceptions in the same catch clause and also re-throw final exceptions without declaring the method with the "throws" clause.  More Precise Rethrow allows you to catch a high level exception instead of each possible exception, but when you re-throw this caught exception, the correct sub-class is thrown instead of the higher level exception. This merits more detailed explanation and a separate post.


Fork & Join threading enhancements
New Fork / Join framework as an implementation of the ExecutorService to help take advantage of mulit-core / multi-processor machines.


NIO 2.0 & File system access enhancements
NIO 2.0 & File system related changes make it easier for traversing file system trees and access file properties.
There are numerous changes and these could be a good candidate for a separate book in itself.


Check out the Summary of Java 5 features that are also hold good and are very useful.

Java Diamond "<>" operator

As part of Project Coin - Language enhancements, Java 7 has introduced the Diamond operator "<>".
In reality, this is just a short cut for a simpler type inference for generic instance creation.
So instead of this:

List<String> stringList = new ArrayList>String>();

one can use this in Java7:
List<String> stringList = new ArrayList<>();

So you say "big deal"?! The real benefits show when the type being inferred is very complicated and has multiple types nested in it like:
Map<String, List<Pair<String,BigDecimal>> myMap = new HashMap<>();

You are saved from repeating the same thing - less typing and less errors!

Friday, July 29, 2011

Eclipse support for Java7

Good news for Eclipse users is that all new builds of Eclipse 3.7.1, 3.8 and 4.2 will now fully support Java 7.
Earlier development of Java7 support in Eclipse was being done in BETA_JAVA7 branch which now has been fully merged into the HEAD and the R3_7_maintenance branch.


So the implication is that if you want Java7 support, you need to move to the latest builds of Eclipse Indigo (3.7.x) or higher. Cannot use Eclipse Helios (3.6.x) or even the initial versions of Indigo as the older JDT & Core packages do not understand the new Java7 features as Eclipse uses its own compiler and the ones built into older versions of Eclipse do not support Java 7. Also, as noted in the Project Plan For Eclipse Project, version Helios, support for Java 7 is deferred and decoupled from the 3.6 release since Java 7 release will be after the official release of 3.7.

Note that you will need to download a 3.7 maintenance build (>= M20110729-1400), a 3.8 build (>= I20110729-1200), a 4.1 maintenance build (coming soon) or a recent 4.2 build (>= I20110729-0200) to get Java7 support in Eclipse.

Java 7 GA release finally available

Java 7 was finally release into the wild today and made "GA" - Generally Available!
Download the latest from here.
Here's a very high level list of the new features/changes that made into Java7:

VM
  • Support for dynamically-typed languages using the new InvokeDynamic instructions
  • Strict class-file checking

Language
  • Small language enhancements from Project Coin like Strings in switch statements, try-with-resources statements, diamond operator, etc.

Core
  • Upgrade class-loader architecture to avoid deadlocks in non-hierarchical class-loader topologies
  • Concurrency and collections updates in form of a lightweight fork/join framework, flexible and reusable synchronization barriers, transfer queues, concurrent linked double-ended queues, and thread-local pseudo-random number generators

Internationalization
  • Support for Unicode 6.0
  • Separate handling of locales to separate formatting locales from user-interface language locales

I/O & Networking
  • New APIs for filesystem access, scalable asynchronous I/O operations, etc
  • New NIO.2 filesystem provider for zip and jar files
  • API for the Stream Control Transmission Protocol (SCTP) on Solaris
  • SDP (Sockets Direct Protocol) support for reliable, high-performance network streams over Infiniband connections on Solaris and Linux
  • Networking code modified to use the Windows Vista IPv6 stack, when available, in preference to the legacy Windows stack
  • Support for Transport Layer Security version 1.2

Security & Cryptograpphy
  • Implementation of the standard Elliptic Curve Cryptographic (ECC) algorithms to allow Java programs to support it out of the box

Database Connectivity
  • JDBC 4.1 and Rowset 1.1

Client
  • New Java2D graphics pipeline based upon the X11 XRender extension, which provides access to much of the functionality of modern GPUs
  • New platform APIs for features originally implemented in the 6u10 release namely Translucent and shaped windows, and heavyweight/lightweight component mixing
  • Cross-platform Nimbus look-and-feel for Swing
  • SwingLabs JXLayer component decorator added to the platform
  • New Gervill sound synthesizer created and made available

Web
  • Upgrade of the components of the XML stack to the most recent stable versions: JAXP 1.4, JAXB 2.2a, and JAX-WS 2.2

Management
  • Enhanced MBeans to report the recent CPU load of the whole system, the CPU load of the JVM process, and to send JMX notifications when GC events occur 

Pheww - that was a long list to say the least ;) No wonder the release date for Java7 was a very difficult moving target.
I will be putting out a detailed post on each of the features soon - so keep watching this space!

Thursday, July 21, 2011

Conditional Breakpoints in Eclipse

If you have a big data set that you are using to test changes that apply to specific scenarios or rows, Eclipse conditional breakpoints can help to make life easier and simpler.

In Debug View (obviously!), right-click on the breakpoint that you want to make conditional and in the window that opens up, check "Enabled" box and then the "Conditional" box. This enables the textarea below it where you can enter any valid java expression which should trigger this breakpoint when true.

Optionally, you can also check the "Hit count" box and enter a positive number to make this breakpoint trigger after that many number of iterations.

Wednesday, May 25, 2011

Change format of Date displayed in SQL Developer

To change the format of Date column displayed in SQL Developer worksheets (output of SQL queries) do the following:
  1. Select Tools > Preferences
  2. Expand the Database section
  3. In the NLS Date format field, enter the desired date format as supported by Oracle
My preferred format is DD-MON-RR HH24:MI:SS

Tuesday, April 5, 2011

Array Equality in JUnit

Till JUnit4.2.*, the only way to compare equality of arrays was to use the following snippet of code:

assertTrue(java.util.Arrays.equals(primitiveArray1, primitiveArray2));

JUnit4.3.* added the assertArrayEquals methods but surprisingly omitted a method to compare arrays of primitive doubles so, one had to fall back to the above mentioned way to compare them.

This important feature was added in JUnit4.6 so if you are using that or a later version, you can do the following:
assertArrayEquals(doubleArray1, doubleArray2, delta)
where delta is the allowed tolerance.

The advantage with using the assertArrayEquals method over the previous method is that this method clearly indicates the first element which differed. For example, when the below basic test is run, it gives the error message:
arrays first differed at element [2]; expected:<2.3124> but was:<2.3224>

Here is a sample class file showing implementation of the above test:

import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;

public class AAETest {

    @Test
    public void testAAEDouble() {
     double[] da1 = {1.002d, 1.234d, 2.3124d, 3.91293d};
     double[] da2 = {1.003d, 1.2345d, 2.3224d, 3.91293d};
     double tol = 0.001d;
     assertArrayEquals(da1, da2, tol);
    }
}

Tuesday, December 21, 2010

11 Free Productivity Tools for the office

Here's a list of 11 Free Tools to increase productivity at Work:
  1. 7-Zip:
    Category: Compression/Decompression
    Details: Compression utility that can handle almost all possible formats
    URL: http://www.7-zip.org
  2. Eclipse:
    Category: IDE
    Details: Very popular IDE that supports a vast array of languages and configurations
    URL: http://www.eclipse.org
  3. FileZilla:
    Category: FTP Client (& Server)
    Details: FTP Client and server with lots of options
    URL: http://filezilla-project.org
  4. PuTTY:
    Category: Telnet/SSH
    Details: Very simple but powerful Telnet/SSH client
    URL: http://www.chiark.greenend.org.uk/~sgtatham/putty/
  5. PuTTy Connection Manager:
    Category: Telnet/SSH
    Details: Allows docking of multiple PuTTY session windows as Tabs and allows user to create a database of connections that includes user names, passwords, script to run after login, etc.
    URL: http://puttycm.free.fr
  6. Notepad++:
    Category: Editor
    Details: Very simple, but powerful and full featured editor that supports syntax highlighting, plug-ins, macros, regexes, etc.
    URL: http://notepad-plus-plus.org
  7. OpenOffice:
    Category: Office Software
    Details: Full featured replacement for the cos$tly M$ Office Suite of products. Includes software for word processing, spreadsheets, presentations, graphics, databases and more.
    URL: http://www.openoffice.org
  8. PDFCreator:
    Category: Office Software
    Details: Create PDF files from any application.
    URL: http://www.pdfforge.org/pdfcreator/
  9. VirtualDimension:
    Category: Desktop Manager
    Details: Fast and full-featured virtual desktop manager that allows you to create virtual desktops on Windows just like X-Win.
    URL: http://virt-dimension.sourceforge.net
  10. VistaSwitcher:
    Category: Task Manager
    Details: Replaces the default Windows Alt-Tab dialog with a nice box that shows a list of all running tasks, with their names and preview snapshots, and enables the user to take actions on them using the mouse and keyboard shortcuts.
    URL: http://www.ntwind.com/software/vistaswitcher/
  11. WinMerge:
    Category: Development
    Details: Visual diff and merge tool for Windows that can compare both folders and files
    URL: http://winmerge.org

Other good free softwares that I also considered were:
  1. PSPad:
    Category: Editor
    Details: Another powerful and full featured editor that supports syntax highlighting, plug-ins, macros, regexes, etc.
    URL: http://www.pspad.com
  2. PDFReDirect:
    Category: Office Software
    Details: Another simple software to create PDF files.
    URL: http://www.exp-systems.com
  3. DiffMerge:
    Category: Development
    Details: Visual diff and merge tool for Windows, Mac OS X and Linux that can compare both folders and files
    URL: http://www.sourcegear.com/diffmerge/
  4. Toad Free:
    Category: Database Access
    Details: Free version of the powerful Toad for Oracle with a few features disabled.
    URL: http://www.toadworld.com/Freeware/tabid/680/Default.aspx
  5. SQLDeveloper for Oracle:
    Category: Database Access
    Details: Oracle client provided by Oracle
    URL: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html

Please let me know if you see other good free software worthy of including in the above list!

Wednesday, September 22, 2010

How to use Syntax Highlighter 3 in Blogger

Syntax Highlighter version 3.0.83 has been released and there are quite a few changes in the way things work now. I realized this when the rendering on this site broke after I modified it to use the latest release. So, here is the steps required to setup the "hosted" version of the latest Syntax Highlighter (version 3.0.83) and integrate with your Blogger/Blogspot blog.

Installation

  1. Navigate to Dashboard > Design > Edit HTML
  2. Backup the current template by clicking on the link Download Full Template
  3. In the textarea, press CTRL+F to find the code </head>
  4. Copy the below code and paste it just above
    <!-- Syntax Highlighter Additions START -->
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
    
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
    
    <script language='javascript' type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
    </script>
    <!-- Syntax Highlighter Additions END -->
    
  5. Preview your changes and make modifications as required
  6. Save the template

In the above code, I have put in brushes for the languages that I use frequently. Modify the brushes according to your needs - check the full list of supported brushes here and use whichever you need.

Configuration

Apart from choosing the brushes that you need, there are other configuration parameters that you can setup as well. Check out the details here. More useful ones are the ones that allow you to change the starting line number, highlight specific lines, disable auto-linking of URLs and html-script option to highlight mixture of HTML/XML code.

Apart from these configuration changes, you can change the theme as well. SyntaxHighlighter comes bundled with 7 themes and I personally like the default one. However, you can choose the theme that you fancy the most by simply replacing the name of the theme in this line:
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>

So you can replace shThemeDefault in the above line with any one of the following themes:
  1. Django - shThemeDjango
  2. Eclipse - shThemeEclipse
  3. Emacs - shThemeEmacs
  4. Fade to Grey - shThemeFadeToGrey
  5. Midnight - shThemeMidnight
  6. RDark - shThemeRDark

Usage

To use it in your blog post, there are a couple of things that need to be done.
  1. Escape all code by replacing any occurrences of:
    1. < with &lt;
    2. > with &gt;
  2. Enclose the escaped code between <pre class="brush:[brush_name];[optional_params]"> and </pre>
  3. Setup the proper brush name (based on the code being highlighted) in the opening pre tag. Using the correct brush will ensure proper highlighting of the code

New Features in 3.0.83

The new version brings with it quite a few new features - here's an overview:
  • Auto-Loading of Brushes

    Now all the brushes need not be pre-loaded on every page. You can load only the required brushes on the pages that need those brushes. Use the shAutoloader.js and then load the brushes as required
    For more details on using this feature, check out the instructions here. Note that this might not be so useful for a blogger account as we do not modify the javascript for each page/post.
  • No usage of Flash

    Earlier, Flash was being used to copy the code to clipboard. This has now been removed and a simpler & better way to do this has been implemented. Also, the user can now simply double-click anywhere in the code to select it and then use the standard CTRL+C to copy it.
  • Code copy without line numbers

    Now the copied code excludes line numbers and the extra leading tabs/spaces to make it usable directly - very convenient!
  • Add Title

    Now you can add a title to the code block by title="[title_name]"
parameter to the pre tag.

  • More under the hood

    More improvements and changes under the hood like better CSS support, easier integration with CommonJS & node.js, etc.
  • Monday, September 20, 2010

    Search & replace text in multiple files in Unix

    To search a particular string in multiple files and replace all occurrences with a new string, you can use the following handy Perl one-liner:

    perl -pi -e 's#search_string#replace_string#g' *.php
    

    Here, the -p switch wraps the script inside a loop, executing once for each input file which is denoted by the last arguement *.php.

    The -i switch allows inline modification of the file; you can optionally save a backup of the original file by providing the backup file name template after this switch as -i *.bak.

    The -e switch executes the following piece of code.

    The string of code 's#search_string#replace_string#g' searches for search_string and replaces it with replace_string globally. You can use any other character like "/" to delimit the search & replace strings. Remember to replace the place-holder text with the actual text and also escape it properly.

    Friday, July 16, 2010

    Interview Tips

    Came across a few good articles on how to prepare for interviews especially aimed at Google. These make very good reads even if you are not planning on attending any interviews any time soon!

    LinkWithin

    Related Posts Plugin for WordPress, Blogger...