0 TIP: Generate a pairs of public and private keys

Tuesday, October 29, 2019 Labels: , , , , ,
In Java, The KeyPairGenerator class is used to create a pair of private/public keys. Java supports below three basic types of algorithms with keysize in parenthesis:

  1. DiffieHellman (1024)
  2. DSA (1024)
  3. RSA (1024, 2048)




import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;

public class GenerateKeysEncoded {

 private KeyPairGenerator keyGen;
 private KeyPair pair;
 private PrivateKey privateKey;
 private PublicKey publicKey;

 public GenerateKeysEncoded(int keylength, String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
  this.keyGen = KeyPairGenerator.getInstance(algorithm);
  this.keyGen.initialize(keylength);
 }

 public void createKeys() {
  this.pair = this.keyGen.generateKeyPair();
  this.privateKey = pair.getPrivate();
  this.publicKey = pair.getPublic();
 }

 public PrivateKey getPrivateKey() {
  return this.privateKey;
 }

 public PublicKey getPublicKey() {
  return this.publicKey;
 }

 public void writeToFile(String path, byte[] key) throws IOException {
  File f = new File(path);
  f.getParentFile().mkdirs();

  FileOutputStream fos = new FileOutputStream(f);
  fos.write(key);
  fos.flush();
  fos.close();
 }

 public static void main(String[] args) {
  GenerateKeysEncoded gk;
  try {
   gk = new GenerateKeysEncoded(1024, "RSA");
   gk.createKeys();
   gk.writeToFile("publicKey", gk.getPublicKey().getEncoded());
   gk.writeToFile("privateKey", gk.getPrivateKey().getEncoded());
  } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
   System.err.println(e.getMessage());
  } catch (IOException e) {
   System.err.println(e.getMessage());
  }

 }

}


Read more

0 TIP: how to create private docker registry for your company

Thursday, October 24, 2019 Labels: , , ,
For beginners, they look towards docker hub for the registry. But, what if the company has sensitive applications, which can't be hosted even privately on docker hub. The novice engineer runs out of options. So here is the tip for the day.

You can have your very own private registry. The good thing is, it would be another running container.

You can do this on your development machine, as well as on your server. But keep in mind these few points.

1. Default port would be 5000 for the registry

2. Locally, you are not bothered about the security, but for actual production-grade Docker registry, you should be running it on 443 or over SSL.

3. Further, you can restrict its access using basic-authentication as well.

4. Last but not least, point the storage to Amazon S3 or IBM Cloud Object Storage

Best of luck with containerization!
Read more

0 TIP: Batch Updates with Spring JdcbTemplate

Wednesday, October 23, 2019 Labels: , , , , ,
Spring JdbcTemplate offers the following method to do multiple updates.


int[] org.springframework.jdbc.core.JdbcTemplate.batchUpdate(String sql, BatchPreparedStatementSetter pss) throws DataAccessException

Rules:
1. Issue multiple update statements on a single PreparedStatement, using batch updates and a BatchPreparedStatementSetter to set values.
2. Will fall back to separate updates on a single PreparedStatement if the JDBC driver does not support batch updates.

Specified by: batchUpdate(...) in JdbcOperations
Parameters:
sql defining PreparedStatement that will be reused. All statements in the batch will use the same SQL.
pss object to set parameters on the PreparedStatement created by this method
Returns:
an array of the number of rows affected by each statement
Throws:
DataAccessException - if there is any problem issuing the update

Here is a reference code, where jdbcTemplate is already @Autowired.




public int[] insertPersons(List persons) {
    return jdbcTemplate.batchUpdate(
        "insert into staging.storage_insight_call_detail(first_name, middle_name, last_name) values(?, ?, ?)",
        new BatchPreparedStatementSetter() {

          public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setString(1, persons.get(i).firstName());
            ps.setString(2, persons.get(i).middleName());
            ps.setString(3, persons.get(i).lastName());
          }
          public int getBatchSize() {
            return persons.size();
          }

        });
}
Read more

0 Getting the Generated Key using Spring's JdbcTemplate

Monday, October 21, 2019 Labels: , , , , , ,
It is pretty straight forward to have the generated primary key using simple JDBC, but what to do, when you are using Spring's JDBCTemplate.

This is how it's done:

KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(
        new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps =
                    connection.prepareStatement(INSERT_SQL, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, callString);
                ps.setString(2, storageInsightDTO.getMetadata().getRc());
                return ps;
            }
        },
        keyHolder);

 System.out.println("generated key: " + keyHolder.getKey());


Where
1.  INSERT_SQL is your native SQL Insert Query

2. Statement.RETURN_GENERATED_KEYS is required to get the generated key.

I hope, you know basic Spring, if you come here and looking for the generated key, then above code is going to be very helpful for you.



Read more

0 F.I.R.S.T Principles of Unit Testing

Labels: , ,


In simple words, F.I.R.S.T Principles of Unit Testing stand for:

Fast: Tests should run quickly.

Independent: Tests should be independent of each other.

Repeatable: Should be able to run in all environments.

Self-validating: Tests should have boolean output. Either they pass or fail.

Timely: Tests should be written in a timely fashion.

Usage of JUnit is encouraged as it incorporates the above-mentioned features.

Read more

0 Tip: How to handle custom database schema name while configuring Quartz with Spring Boot

Saturday, October 19, 2019 Labels: , , ,

Plenty of tutorials are there on how to integrate Quartz Scheduler with Spring-Boot.  You can also easily find all the SQL scripts on Github. But you might get into difficulty if you have to create these tables in a custom schema, other than the default.

Here goes the tip:

Add this line in the application.properties


spring.quartz.properties.org.quartz.jobStore.tablePrefix=schemaname.QRTZ_

Or

spring.quartz.properties.org.quartz.jobStore.tablePrefix=mySchema.QRTZ_


After, this, Spring Boot would be able to recognize where your Quartz related tables are.

Happy development!
Read more

1 Guide to Image Compression and Colour format

The PNG format is pretty versatile. It can contain bitmaps indexed with palettes in both 8-bit and 4-bit format, bitmaps in grayscale, bitmaps in 32bit colour using alpha masks and so on.

The first thing you have to do is make sure that each image you use is converted to it’s the most efficient colour format. If it’s pixeled art, you can reduce the colours in an indexed palette to include just the ones needed. If it has anti-aliased edges, you must save it in 32bit colour format to make use of the alpha channel (24 bit for the bitmap data, 8 bit for the alpha channel). 32bit images are always larger in byte size, but of course, they look nicer. Even if you’re using 32bit images, it can be good to reduce the number of different colours used as this makes the bitmap data easier to compress. An easy way of doing this is to use the “adjust - posterize” feature in Photoshop.

Note: It is possible to create 8bit indexed PNG files that use an 8-bit alpha channel using a program called PNGOutWin, but it’s not commonly supported and I’ve heard of problems with such images on certain phone models. (Anyway, thanks to Ed for pointing this out)

I use the “save for web” option in Photoshop when I first export my images for use in J2ME games, it is really good at producing indexed images.

The PNG format has support for a lot of descriptive “chunks” that are not really needed just for drawing them in J2ME. These can be removed using PNG optimizer tools. Also, the PNG format uses the deflate algorithm for compression (just as ZIP does) so by using a tool that recompresses the data chunks using a more efficient deflate you can get even smaller PNGs. The PNG format also has support for different “filters” that varies the way the image data is stored. This can be used to optimize a PNG image for a smaller size as well.

You can often reduce the total size of your images by joining them together into bigger images (that looks like film strips). The ground rule of compression is that data compresses better when the compression algorithm has more data to work with (instead of compressing images individually). However, sometimes it’s better to leave the images separate, as they can be using different optimized 8-bit and 4-bit palettes. You have to try different approaches to find what combination works best for your images.
Read more
 
Waqas Sadiq © 2014