In the previous example we use JSONObject to directly put key-value pairs to create JSON string, using the various put() methods. Instead of doing that, we can also create JSON from a Map object. We create a Map with some key-value pairs in it, and pass it as an argument when instantiating a JSONObject.
These are the steps for creating JSON from a Map:
Create a Map object using a HashMap class.
Put some key-value pairs into the map object.
Create a JSONObject and pass the map as argument to its constructor.
Print the JSONObject, we call object.toString() to get the JSON string.
Let’s try the following code snippet.
package org.kodejava.json;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class JSONFromMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "Alice");
map.put("age", "20");
JSONObject object = new JSONObject(map);
System.out.println(object);
}
}
JSch is a pure Java implementation of SSH-2. SSH (Secure Shell) is a cryptographic network protocol for operating network services securely over an unsecured network. The following code snippet shows you how to open a connection to an ssh server.
Place your cursor where you want to add a merge field.
Click the Insert menu, Quick Parts, Fields…
In the Field names select MergeField and enter the field name and press OK.
To create merge field for image you need to prefix the field name with Image:
When finished save the document.
The Mail Merge Code Snippet
The code snippet reads the mail merge template from a file called Receipt.docx. For the image we use a duke.png. Both of these files must be placed in the /src/main/resources directory in your maven project so that the code can read it.
package org.kodejava.example.spire;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.reporting.MergeImageFieldEventArgs;
import com.spire.doc.reporting.MergeImageFieldEventHandler;
import java.awt.Dimension;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MailMergeExample {
public static final Locale LOCALE = new Locale("id", "ID");
public static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd-MMMM-yyyy", LOCALE);
public static final NumberFormat NUMBER_FORMAT = NumberFormat.getCurrencyInstance(LOCALE);
public static void main(String[] args) {
String[] fieldNames = new String[]{
"academicYear",
"registrationNumber",
"fullName",
"gender",
"telephone",
"address",
"paymentAmount",
"inWords",
"paymentDate",
"receivedBy",
"picture"
};
String[] fieldValues = new String[]{
"2021/2022",
"0001/REG/2021",
"Foo Bar",
"M",
"081234567890",
"Sudirman Street 100",
NUMBER_FORMAT.format(1575000),
"One Million Five Hundred Seventy Five Thousand",
DATE_FORMAT.format(new Date()),
"John Doe",
"/duke.png"
};
try {
Document document = new Document();
document.loadFromStream(MailMergeExample.class.getResourceAsStream("/Receipt.docx"), FileFormat.Auto);
document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
@Override
public void invoke(Object o, MergeImageFieldEventArgs field) {
field.setPictureSize(new Dimension(66, 88));
String path = field.getImageFileName();
if (path != null && !path.isEmpty()) {
try {
field.setImage(MailMergeExample.class.getResourceAsStream(path));
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
document.getMailMerge().execute(fieldNames, fieldValues);
String fileName = "Receipt.pdf";
FileOutputStream fos = new FileOutputStream(fileName);
document.saveToStream(fos, FileFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Running the code will create a file called Receipt.pdf with the content as shown in the image below.
The following Android code snippet shows you how to customize the input value format of an EditText component for accepting currency number. To format the input value we will create a text watcher class called MoneyTextWatcher, this class implements of the android.text.TextWatcher interface. In the MoneyTextWatcher class we implement the afterTextChanged(EditText s) method, in this method the currency formatting takes place.
To apply this text watcher class we call the the addTextChangedListener() method of the EditText object of the currency input and pass an instance of MoneyTextWatcher. Below is the working example of the activity class and the text watcher.
When the EditText input is changed the afterTextChanged() method of the text watcher will be called. In this method we’ll take the input text and format the input value with currency symbol and a number, this is done by the NumberFormat.getCurrencyInstance() object. The static helper method parseCurrencyValue() will get the number part of the EditText by removing the currency symbol and return the input number.
package org.kodejava.android;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Objects;
public class MoneyTextWatcher implements TextWatcher {
public static final NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("id", "ID"));
private final WeakReference<EditText> editTextWeakReference;
public MoneyTextWatcher(EditText editText) {
editTextWeakReference = new WeakReference<>(editText);
numberFormat.setMaximumFractionDigits(0);
numberFormat.setRoundingMode(RoundingMode.FLOOR);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
EditText editText = editTextWeakReference.get();
if (editText == null || editText.getText().toString().equals("")) {
return;
}
editText.removeTextChangedListener(this);
BigDecimal parsed = parseCurrencyValue(editText.getText().toString());
String formatted = numberFormat.format(parsed);
editText.setText(formatted);
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
public static BigDecimal parseCurrencyValue(String value) {
try {
String replaceRegex = String.format("[%s,.\\s]", Objects.requireNonNull(numberFormat.getCurrency()).getDisplayName());
String currencyValue = value.replaceAll(replaceRegex, "");
return new BigDecimal(currencyValue);
} catch (Exception e) {
Log.e("MyApp", e.getMessage(), e);
}
return BigDecimal.ZERO;
}
}
The following animation is the result of our code snippet above.
The following code snippets shows you how to get a Device ID of an Android phone. To be able to read the Device ID you need to update the AndroidManifest.xml file and add the READ_PHONE_STATE permission.
In this example we are going to create a simple Android application to print texts to a Bluetooth thermal printer. We’ll be using the Android library for ESC/POS Thermal Printer to develop this example.
We begin by creating an Android project with an Empty Activity. After the project is created we need to edit the app/build.gradle to add the required dependencies and the repository from which it will be downloaded.
Let’s now jump to the code snippet that will actually print our store receipt to the printer. The steps are quite simple.
After added the uses-permission in the AndroidManigest.xml we also need to check permission in the application, you’ll do it like this.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH}, MainActivity.PERMISSION_BLUETOOTH);
}
Open the connection to Bluetooth printer by calling the selectFirstPaired() method of the BluetoothPrintersConnections class. This will give us an instance of BluetoothConnection. If the connection is good we create an instance of EscPosPrinter by passing some parameters like the connection, printer dpi, width in millimeter and the printer’s number of character per line.
This example show you how to connect and read data from MySQL database directly from Android. The following steps and code snippet will show you how to do it.
Add the MySQL JDBC driver into your project dependencies. Open the app/build.gradle file and add the dependency.
If you want to connect to MariaDB you can change the JDBC driver dependency using 'org.mariadb.jdbc:mariadb-java-client:1.8.0', also update the JDBC url in the code snippet by replacing mysql with mariadb.
Next, add internet permission to our application in AndroidManifest.xml file.
Let’s connect, read data from the database and display the information on the screen. In the code snippet we create an AsyncTask to read the information from the database. In the doInBackground() method we open a connection to the database, create a PreparedStatement, execute a query, get a ResultSet and read the information from it. We pack the data into a Map and return it.
After the doInBackground() method finish its execution the onPostExecute() method will be called. In this method we take the result, the Map returned by the doInBackground() method, and set the values into the TextView components for display.
I need to create a Microsoft Word Mail Merge document in my Java Spring MVC application. But running it in Ubuntu server resulting in a document that missing the default font use in the document, which is the Calibri font. So I need to install the font in Ubuntu to make the document looks as expected.
Here what I need to do to install the font in my Ubuntu box. Starts by updating the repository package list to get latest packages information for upgrades or new package installation.
sudo apt-get update
Then install FontForge in our system. FontForge is a free and open source font editor, but in this case it will help to do the font conversion in the installation script on the upcoming step.
sudo apt-get install fontforge
Install the Microsoft Cabinet file un-packer. This is required for the next script to successfully install the fonts.
In this example you will learn how to create a generic class in Java. In some previous post in this blog you might have read how to use generic for working with Java collection API such as List, Set and Map. Now it is time to learn to create a simple generic class.
As an example in this post will create a class called GenericMachine and we can plug different type of engine into this machine that will be use by the machine to operate. For this demo we will create two engine type, a DieselEngine and a JetEngine. So let’s see how the classes are implemented in generic.
package org.kodejava.generics;
public class GenericMachine<T> {
private final T engine;
public GenericMachine(T engine) {
this.engine = engine;
}
public static void main(String[] args) {
// Creates a generic machine with diesel engine.
GenericMachine<DieselEngine> machine = new GenericMachine<>(new DieselEngine());
machine.start();
// Creates another generic machine with jet engine.
GenericMachine<JetEngine> anotherMachine = new GenericMachine<>(new JetEngine());
anotherMachine.start();
}
private void start() {
System.out.println("This machine running on: " + engine);
}
}
Now, for the two engine class we will only create an empty class so that the GenericMachine class can be compiled successfully. And here are the engine classes:
package org.kodejava.generics;
public class DieselEngine {
}
package org.kodejava.generics;
public class JetEngine {
}
The <T> in the class declaration tell that we want the GenericMachine class to have type parameter. We also use the T type parameter at the class constructor to pass the engine.
The following code snippet will show you how to convert the old java.util.TimeZone to java.time.ZoneId introduced in Java 8. In the first line of our main() method we get the default timezone using the TimeZone.getDefault() and convert it to ZoneId by calling the toZoneId() method. In the second example we create the TimeZone object by calling the getTimeZone() and pass the string of timezone id. To convert it to ZoneId we call the toZoneId() method.
To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId to TimeZone by using the TimeZone.getTimeZone() method and pass the ZoneId.systemDefault() which return the system default timezone. Or we can create ZoneId using the ZoneId.of() method and specify the timezone id and then pass it to the getTimeZone() method of the TimeZone class.