Tagged: Java

Java code to wrap text at a right margin while not breaking HTTP or HTTPS URLs

From the source code of EmailTweetor for Desktop.

Output of text wrapped by the Java code routine.

wrapString ignores hyperlinks, spaces in the beginning of the line and chops of big words.

Recently, I released a command-line version of my Android Twitter client. This program was a more intensive console program than TweetsToRSS. So, I had to write a dedicated text-wrapping function. A function in the Apache Commons Text library was suggested online as a good option. It was a big library and also needed another library Apache Commons Lang3. Hence, I had to write my own routine.

  • It wraps text at the right side after a specified number of letters.
  • Words are broken and hyphenated if they end up near the end of the line. The Apache Commons library uses a more elegant way of not breaking words and moving them to the next line. Of course, this required that library to have an extra overload for breaking words longer than the specified line length.
  • Hyperlinks should not be broken and should appear in full because Linux terminals recognize hyperlinks make them clickable.
  • It should ignore spaces when they appear at the beginning of the line.

Here is the code:

static String wrapString(String asText, int aiLength) {
	StringBuffer sBuff = new StringBuffer("");
	if (aiLength < 3) {
		miBREAK_AT = 72;
	} else {
		miBREAK_AT = aiLength;
	}
	
	if ((asText != null) && (!asText.trim().contentEquals(""))) {
		if (asText.length() <= miBREAK_AT) {
			return(asText);
		} 
		int i = 0, j = 0, k = 0, n = asText.length();
		for (; i < n; i++) {
			if (((i+"https://".length() < n) && 
					 (asText.substring(i,  i+"https://".length()).contentEquals("https://"))) ||
					((i+"http://".length() < n) && 
					 (asText.substring(i,  i+"http://".length()).contentEquals("http://")))) {
				sBuff.append(asText.substring(j, i));
				for (k = i; k < n; k++) {
					if ((!asText.substring(k, k+1).contentEquals(" ")) &&
							(!asText.substring(k, k+1).contentEquals("\n")) &&
							(!asText.substring(k, k+1).contentEquals("\r")) &&
							(!asText.substring(k, k+1).contentEquals(";"))) {
						sBuff.append(asText.substring(k, k+1));
					} else {
						break;
					}
				}
				i = k;
				j = k;					
				if ((i < n) && (asText.substring(i, i+1).contentEquals(" "))) { ++j; } } else { if ((i - j) == miBREAK_AT) { // reached max sBuff.append(asText.substring(j, i)); j = i; if (i > 0) {
						if ((asText.charAt(i-1) != ' ') &&  
								Character.isLetter(asText.charAt(i-1)) && 
								Character.isLetter(asText.charAt(i))) {
							sBuff.append("-");
						} else if (asText.substring(i, i+1).contentEquals(" ")) {
							++j;
						}
						sBuff.append("\n");
					}					
				} else if ((i > 0) && (asText.substring(i, i+1).contentEquals("\n"))) { // reached eol
					sBuff.append(asText.substring(j, i));
					j = i;
				}
			}
		}
		if ((n - i) < miBREAK_AT) {
			sBuff.append(asText.substring(j));
		}
	}	
	return(sBuff.toString());
}

This article has been posted to CodeProject.com.

Advertisements

Solution to OpenJDK’s “Connection error sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target” error

Today, I downloaded Open JDK 10 to test it against my NetCheck JAR file. It did not work. I got this error:

Connection error sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

It seems that the certificat store bundled with the open-source project does not have information on all CAs. So, I copied the certificate store files (cacerts and blacklisted.certs) from Oracle Java JRE directory and the problem got resolved.

Copy the cacert and blacklisted.certs files from Oracle Java.

Source code for CellTrack – My J2ME Cell Broadcast System (CBS) Tracking App

Today, I was finally able to get hold of the JAR file of my CellTrack J2ME. As I had mentioned earlier, all my J2ME apps had vanished from my computer. There was a possibility decompile Java class file in the JAR and extract the source code but JAR file for the CellTrack JAR was missing. I could trace all JAR files for all the other apps that I had created.

However, I realized that when I installed the app to my Motorola V3 RAZR phone, it received the JAR and the JAD file. There were two app that did the same thing for some reason. So, the JAR was in the phone. However, getting it back was not easy.

The Motorola Mid-Way app will install JARs and JADs but will not extract it. There was however other apps that could do it. When V3 was released, it caused quite a sensation among the public and was sold in large numbers. Several people had created apps to tinker with it. There was one guy who had replaced the startup GIF file with one modified to look like Windows XP. He had also added the Windows Start wave file to it making the effect complete.

Anwyay, the tool to read the Motorola’s internal file system is P2K Commander. This is now an abandoned software. The installed JAR will be renamed in an unrecognizable manner. You need to open each of them in a archive viewer such as IZarc. Then, use JAD Decompiler, another by Pavel Kouznetsov, which is another abandoned software. This decrypted the class file in the JAR file when used with the -sjava parameter.

CBS-based cell-tracking J2ME app running on Motorola V3 RAZR

So, now, here is the source code:

// Source File Name:   CellTrack.java
// (C) V. Subhash, 2013-2014.
/// All rights reserved.

import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.wireless.messaging.*;

public class CellTrack extends MIDlet
    implements MessageListener, CommandListener {

  private Display display;
  MessageConnection msgconn;
  TextMessage txtmsg;
  String from;
  String Msg;
  List lstCells;
  Date dt;
  Command cmdExit;

  public CellTrack(){
  }

  protected void destroyApp(boolean unconditional)
      throws MIDletStateChangeException {
    notifyDestroyed();
  }

  protected void pauseApp() {
  }

  protected void startApp()
      throws MIDletStateChangeException {
    display = Display.getDisplay(this);
    lstCells = new List("Cell Towers", 1);
    cmdExit = new Command("Exit", 7, 1);
    lstCells.addCommand(cmdExit);
    lstCells.setCommandListener(this);
    display.setCurrent(lstCells);
    setupListening();
  }

  public void setupListening() {
    try {
      if (msgconn == null) {
        msgconn = (MessageConnection)Connector.open("cbs://:50");
        msgconn.setMessageListener(this);
      }
    } catch(IOException e) {
      lstCells.append("Error: " + e.getMessage() + e.getClass().getName(), null);
    }
  }

  public void notifyIncomingMessage(MessageConnection conn) {
    dt = new Date();
    try {
      txtmsg = (TextMessage)msgconn.receive();
    } catch(Exception e) {
      System.out.println(e);
    }
    from = txtmsg.getAddress();
    Msg = txtmsg.getPayloadText();
    lstCells.append(Msg + " \n(" + dt.toString() + ")", null);
    lstCells.setTicker(new Ticker(Msg + " - " + dt.toString()));
  }

  public void commandAction(Command arg0, Displayable arg1) {
    if(arg0 == cmdExit) {
      try {
       destroyApp(false);
      } catch(MIDletStateChangeException e) {
        e.printStackTrace();
      }
      notifyDestroyed();
    }
  }

  public void itemStateChanged(Item item1) {
  }
}

J2ME is dead! Good Bye, Java ME!

Java ME has no future

CBS-based cell-tracking J2ME app running on Motorola V3 RAZR

I was programming on Android when I got the idea that the “Cell Info” or the cell tower information can be used as what someone called “a poor man’s GPS.”
https://www.dropbox.com/s/gzpdizj6h9r34qi/CellTrack.jad?dl=0

“Cell Info” is part of a technology called Cell Broadcast System (CBS). Most cell phone towers broadcast these messages every few minutes. In the CBS messages broadcast by BSNL cell towers, you will find the name of the area. Some providers such as Vodafone or Tata broadcast only commercial messages.

Many Nokia “feature” phones display CBS messages by default. In other phones, CBS can be enabled, although it may be hidden in layers of menu options. (Android does not support CBS because Google (I believe) wants people to use their Maps service instead.)

As I prefer feature phones over “smart” phones, I wanted to write a J2ME app that could keep track of CBS messages. Thus, began my SHORT journey into Java for mobiles. It was short because I ran into a lot of problems – a lot of “no, you can’t do that in J2ME” situations.

Disadavantages of J2ME Apps

  1. J2ME apps run in the foreground. You cannot run them in the background. Minimized Java programs usually get terminated.
  2. J2ME programs will drain your phone battery pretty fast.
  3. Any J2ME app that you create will run under limited security permissions. Java apps provided by the phone manufacturer run with greater permissions.
  4. J2ME by is a limited platform with lot of optional features. Phone providers skimp on the optional features and there is no guarantee that your app will run on all Java-enabled phones.

Oracle, which acquired Java along with Sun, has started work on a new Java ME. It is unlikely to succeed in mobile phone segment, given the onslaught of IOS, Android and others. It may however continue live a faceless existence on set-top boxes, Blu Ray players, and other nondescript devices. Unless of course Oracle starts a new phone platform, which I think it is unlikely to do so.