Dear Coders,

This web page is dedicated to the code lines compiled by the contributors to solve various challenges. You can find valuable examples and snippets within our posts and leave your comments.
M.C.

Replace Turkish Characters in Java – Method 2

1
2
3
4
5
6
7
8
9
public static String clearTurkishChars(String str) {
	String ret = str;
	char[] turkishChars = new char[] {0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E};
	char[] englishChars = new char[] {'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'};
	for (int i = 0; i < turkishChars.length; i++) {
		ret = ret.replaceAll(new String(new char[]{turkishChars[i]}), new String(new char[]{englishChars[i]}));
	}
	return ret;
}
VN:F [1.9.8_1114]
Rating: 10.0/10 (1 vote cast)

Remove Xml/Html Tags from Java String

1
2
3
public String removeXmlTags(String str) {
	return str.replaceAll("\\<.*?\\>", "").trim();
}
VN:F [1.9.8_1114]
Rating: 10.0/10 (1 vote cast)

Replace Turkish Characters in Java – Method 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public String clearTurkishCharacters(String str) {
	if (str != null){
		str = str.replaceAll("&#304;", "\u0130");
		str = str.replaceAll("&#214;", "\u00d6");
		str = str.replaceAll("&#350;", "\u015e");
		str = str.replaceAll("&#220;", "\u00dc");
		str = str.replaceAll("&#199;", "\u00c7");
		str = str.replaceAll("&#286;", "\u011E");
		str = str.replaceAll("&#252;", "\u00fc");
		str = str.replaceAll("&#287;", "\u011f");
		str = str.replaceAll("&#351;", "\u015f");
		str = str.replaceAll("&#231;", "\u00e7");
		str = str.replaceAll("&#246;", "\u00f6");
		str = str.replaceAll("&#305;", "\u0131");
	}
	return str;
}
VN:F [1.9.8_1114]
Rating: 10.0/10 (1 vote cast)

Caps Lock detection with SmartGWT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
	final PasswordItem pwd = new PasswordItem();
	final StaticTextItem sti = new StaticTextItem();
 
//...
		pwd.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				try {
					int keycode = EventHandler.getKeyEventCharacterValue();
					boolean shift = EventHandler.shiftKeyDown();
					if (!shift && keycode >= 65 && keycode <= 90)
						sti.show();
					else 
						sti.hide();
				} catch (Exception e) {
					sti.hide();
				}
			}
		});
//...
 
		sti.setValue("<nobr>&nbsp;Caps Lock is ON &nbsp;</nobr>");
		sti.setCellStyle("hintstyle"); // some style with fancy warning sign...
		sti.setShowTitle(false);
//...
		sti.hide(); // this line must be after DynamicFrom.setItems commnad!
VN:F [1.9.8_1114]
Rating: 9.0/10 (1 vote cast)

Dirty Fix for FFMpeg’s Header Missing Issue

If you suffer from “Header missing” error while decoding your mp3 files with ffmpeg, you can try to change the

libavcodec/mpegaudiodec.c

file as follows, and recompile. (!use AYOR!)

Edit: These changes are required for the ffmpeg in Xuggler 4 and not guaranteed to solve all problems. However ffmpeg in Xuggler 3.4 works fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 
#include "libavformat/id3v1.h"
 
//...
 
static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr, AVPacket *avpkt)
{
    const uint8_t *buf  = avpkt->data;
    int buf_size        = avpkt->size;
    MPADecodeContext *s = avctx->priv_data;
    uint32_t header;
    int out_size;
 
    //++++
    while(1) {
        if (buf_size < HEADER_SIZE){
            av_log(avctx, AV_LOG_DEBUG, "buf_size<header size. Ignore Packet\n");
            return avpkt->size;
            //return AVERROR_INVALIDDATA;
        }
 
        header = AV_RB32(buf);
        if (ff_mpa_check_header(header) < 0) {
            if (buf_size == ID3v1_TAG_SIZE
                && buf[0] == 'T' && buf[1] == 'A' && buf[2] == 'G') {
                s->frame_size = 0;
                return ID3v1_TAG_SIZE;
            }
            //av_log(avctx, AV_LOG_ERROR, "Header missing\n");
            //return AVERROR_INVALIDDATA;
        } else {
            break;
        }
        av_log(avctx, AV_LOG_DEBUG, "Header missing, skipping one byte\n");
        buf++;
        buf_size--;
    }
    // ---
 
    if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
        /* free format: prepare to compute frame size */
        s->frame_size = -1;
        return AVERROR_INVALIDDATA;
    }
 
//
//... rest is the same
//
VN:F [1.9.8_1114]
Rating: 10.0/10 (1 vote cast)

Java Hash to Hex String (for DB Storage)

1
String dbStoreableHash = new java.math.BigInteger(1, MessageDigest.getInstance("SHA").digest(thePassword.getBytes())).toString(16);
VN:F [1.9.8_1114]
Rating: 8.0/10 (1 vote cast)

You can use the following code in your main function to create a datasource with the JNDI name which is usually used by the application server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
            InitialContext ic = null;
            OracleConnectionPoolDataSource ds = null;
            PropertyBase pmap = PropertyBase.getInstance(); 
            try {
                  System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
                  System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
                  ic = new InitialContext();
 
                  ds = new OracleConnectionPoolDataSource();
                  ds.setURL("jdbc:oracle:thin:@my_server_name:1521:SRV_NAME");
                  ds.setUser("username");
                  ds.setPassword("password");
 
                  ic.createSubcontext("jdbc");
                  ic.bind("jdbc/MY_DS_NAME", ds);
            } catch (Exception e) {
                  logger.error("", e);
            }
VN:F [1.9.8_1114]
Rating: 10.0/10 (1 vote cast)

Extending the PostMethod class to support UTF-8 data posting.

1
2
3
4
5
6
7
8
9
10
11
12
13
      public static class UTF8PostMethod extends PostMethod {
            public UTF8PostMethod(String url) {
                  super(url);
            }
 
            @Override
            public String getRequestCharSet() {
                  return "UTF-8";
            }
      }
 
      PostMethod method = new UTF8PostMethod("http://www.google.com");
      method.addParameter(new NameValuePair("q", "something with special chars"));
VN:F [1.9.8_1114]
Rating: 10.0/10 (1 vote cast)

Tooltip for GWT table

If you want to add tooltip for the pure GWT table (com.google.gwt.user.cellview.client.CellTable) we can suggest the following lines;

1
2
3
4
5
6
7
8
9
	Column<String[], SafeHtml> objectNameColumn = new Column<String[], SafeHtml>(new SafeHtmlCell()) {
		@Override
		public SafeHtml getValue(String[] object) {
			String val = (object[index]==null?"":object[index]); 
			return new SafeHtmlBuilder().appendHtmlConstant("<span title='" + 
				new SafeHtmlBuilder().appendEscaped(val).toSafeHtml().asString() + "'>" + val + "</span>").toSafeHtml();
		}
	}; 
	cellTable.addColumn(objectNameColumn, colLabel);
VN:F [1.9.8_1114]
Rating: 10.0/10 (1 vote cast)

Java replaceAll the $ (Dollar sign)

A quick reminder!

If you use Java String’s replaceAll method and not using rgexp groups, do not forget to use Matcher.quoteReplacement method.
Otherwise, you will get “illegal group reference” or “”String index out of range” error when the $ sign occurs in the replacement value (2nd parameter).

Example:

1
2
3
4
5
6
7
8
9
10
	System.out.println("replace the dollar sign".replaceAll("dollar sign", "$"); 
	//Error: "String index out of range: 1"
	System.out.println("replace the dollar sign".replaceAll("dollar sign", "$ sign"));
	//Error: "Illegal group reference"
	System.out.println("replace the dollar sign".replaceAll("dollar sign", Matcher.quoteReplacement("$")));
	//"replace the $"
 
	// or you always have the comfortable StringUtils.replace option
	System.out.println(StringUtils.replace("replace the dollar sign", "dollar sign", "$")); 
	//"replace the $"
VN:F [1.9.8_1114]
Rating: 0.0/10 (0 votes cast)