Reading QR code within PDF file

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Hashtable;
import java.util.Vector;

import javax.activation.DataSource;
import javax.mail.util.ByteArrayDataSource;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

	private String scanQRCode() {

		// Hints for scanning
		Vector<BarcodeFormat> decodeFormat = new Vector<BarcodeFormat>();
		decodeFormat.add(BarcodeFormat.QR_CODE);

		Hashtable<DecodeHintType, Object> hintMap = new Hashtable<DecodeHintType, Object>();
		hintMap.put(DecodeHintType.TRY_HARDER, true);
		hintMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormat);

		MultiFormatReader qrcodeReader = new MultiFormatReader();
		qrcodeReader.setHints(hintMap);

		try {
			// Try lowest DPI first.
			// BufferedImage pageImage = getPageImage(pageIndex, dpiSettings[i]);
			BufferedImage pageImage = getPageImage();
			LuminanceSource source = new BufferedImageLuminanceSource(pageImage);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
			// By using decodeWithState, we keep the Hints that we set earlier.
			Result result = qrcodeReader.decodeWithState(bitmap);
			String text = result.getText();
			return text;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		// This should never happen, ever...
		return null;
	}

	private BufferedImage getPageImage() throws IOException {		
		Path docPath = Paths.get("C:\\NS2\\test_files\\java3.pdf");		
		PDDocument pdfDoc = PDDocument.load(docPath.toFile());
		PDFRenderer renderer = new PDFRenderer(pdfDoc);
		// renderImageWithDPI(page number, image size, format)
		BufferedImage image = renderer.renderImageWithDPI(0, 150, ImageType.BINARY); // entire page info
		pdfDoc.close();
		return image;
	}

Spring REST GET with HttpServletRequest

REST client:


import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.ns.model.UdsTransactionRequest;
import com.ns.model.UfsReferenceNumber;
import com.ns.model.notification.UfsPipeline;
import com.ns.service.ServiceResponse;

	@SuppressWarnings("unchecked")
	private void testGet2() {

		RestTemplate restTemplate = new RestTemplate();

		Long txId = 123456789L;
		String[] array = {"6B","EL","SO","RN","KK"};

		String url = "http://localhost:8080/transaction/references/pipeline/{txId}/?types={types}";

		ServiceResponse<UfsReferenceNumber> response = restTemplate.getForObject(url, ServiceResponse.class, txId, StringUtils.join(array, ","));

		List<UfsReferenceNumber> results = response.getData();
		if (results != null && !results.isEmpty()) {
			for (UfsReferenceNumber a : results) {
				System.out.println("---------------- ID: " + a.getId().getRefNum());
			}
		}
		System.out.println("---------------- END testGet2------------------");
	}

This gives the URL:

http://localhost:8080/transaction/references/pipeline/123456789/?types=6B,EL,SO,RN,KK

The “request.getParameter(“types”);” gets the values from URL “types=6B,EL,SO,RN,KK”.

REST endpoint:

@RequestMapping(value = "/references/pipeline/{txId}/", method = RequestMethod.GET)
public ServiceResponse<UfsReferenceNumber> getReferences(@PathVariable String txId, HttpServletRequest request) {
	ServiceResponse<UfsReferenceNumber> response = new ServiceResponse<>();
	String typesCsv = request.getParameter("types");
	List<String> types = null;
	List<UfsReferenceNumber> references = null;
	if (null != typesCsv && 0 != typesCsv.length()) {
		types = Arrays.asList(typesCsv.split(","));
	}
	try {
		references = repo.getTxnReferenceNumbers(new Long(txId), types);
		if (null != references && !references.isEmpty()) {
			response.setData(references);
		}
	} catch (Exception e) {
	}
	return response;
}

Mongo DB query examples

Greater than:

db.getCollection('StorageContent').find({ $and:[
    {"shardKey" : "7507501"},
    {"cd": {$gte: ISODate("2017-07-02T00:00:00.731Z")}}
]})

Less than:

db.getCollection('NotificationProfile').find({ $and:[
    {createdBy: "hban"}, 
    {deliveryType: "F"}, 
    { 
    "createdDate": {
        $lte: ISODate("2018-11-30")
    }}
]})

Between:

db.getCollection('LogEntry').find({ $and:[
    {
    "time": {
        $gte: ISODate("2017-11-10")
    }}, 
    { 
    "time": {
        $lte: ISODate("2017-11-17")
    }}
]})

Oerder By date:

db.getCollection('notifyEmailSent').find({ $and:[
    {
    "created": {
        $gte: ISODate("2018-12-01 16:00:00:000Z")
    }}
]}).sort({"created": -1})

Exist:

db.getCollection('NotificationProfile').find({ $and:[
    {
        "terminal":{$exists:true}
    },
    {
        "company": '100'
    }
]})

Group By:

db.getCollection('DocumentAudit').aggregate([  
   {  
      "$match":{  
         "tp":"STR",
         "stp":"SSC",
      }
   },
   {  
      "$group":{  
         _id:{  
            "grp":"$grp",
            "com":"$com",
            "tp":"$tp",
            "stp":"$stp"
         },
         count:{  
            $sum:1
         }
      }
   },
   {  
      "$sort":{  
         "_id.grp":1
      }
   },
   {  
      "$sort":{  
         "_id.com":1
      }
   },
   {  
      "$sort":{  
         "_id.tp":1
      }
   },
   {  
      "$project":{  
         "count":1,
         "group":"$_id.grp",
         "company":"$_id.com",
         "type":"$_id.tp",
         "subType":"$_id.stp"
      }
   },
   {  
      "$limit":2000
   }
])

Spring REST PUT form data

Postman image:

REST client:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

	@SuppressWarnings("unchecked")
	private void testPost() {

		String url = "http://localhost:8080/uds-transaction-1.3.0/pipeline/list/";
		RestTemplate restTemplate = new RestTemplate();

		List<Long> list = new ArrayList<Long>();
		list.add(new Long(30284039614L));
		list.add(new Long(30262601669L));
		list.add(new Long(30262662522L));

		UdsTransactionRequest req = new UdsTransactionRequest();
		req.setTrxIdsLong(list);

		HttpEntity<UdsTransactionRequest> request = new HttpEntity<>(req);

		ServiceResponse<UfsPipeline> response = restTemplate.postForObject(url, request, ServiceResponse.class);

		List<UfsPipeline> results = response.getData();
		if (results != null && !results.isEmpty()) {
			for (UfsPipeline a : results) {
				System.out.println("---------------- txNo: " + a.getTxNo());
			}
		}
	}

Endpoint:

	@RequestMapping(value = "/pipeline/list/", produces = "application/json", method = RequestMethod.POST)
	public ServiceResponse<UfsPipeline> getOfficeDocumentEndPoint(@RequestBody UdsTransactionRequest req) {
		ServiceResponse<UfsPipeline> response = new ServiceResponse<>();
		try {
			List<UfsPipeline> list = pipelineRepo.getPipelinesByKeys(req.getTrxIdsLong());
			response.setData(list);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			response.addError(e);
		}
		return response;
	}

Support class:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.ns.model.DataCacheMeta;
import com.ns.model.notification.UfsPipeline;

@JsonInclude(Include.NON_NULL)
public class ServiceResponse<T extends ResponseData> implements Serializable {

	public static final String OK = "ok";
	public static final String ERROR = "error";

	private static final long serialVersionUID = 4579157541957745675L;
	private List<ResponseError> errors;
	private List<T> data;
	private String status = OK;

	public void addError(Exception e) {
		if (null == errors) {
			errors = new ArrayList<>();
		}
		ResponseError error = new ResponseError(null, ResponseError.ERROR, e.getMessage());
		errors.add(error);
		setStatus(ServiceResponse.ERROR);
	}

	public void addData(T dataElement) {
		if (null == data) {
			data = new ArrayList<>();
		}
		data.add(dataElement);
	}

	@JsonSubTypes({@JsonSubTypes.Type(value = ResponseError.class, name = "error")})
	public List<ResponseError> getErrors() {
		return errors;
	}

	public void setErrors(List<ResponseError> errors) {
		this.errors = errors;
	}

	@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
	@JsonSubTypes({ @JsonSubTypes.Type(value = DataCacheMeta.class, name = "DataCacheMeta"),
			@JsonSubTypes.Type(value = UfsPipeline.class, name = "UfsPipeline")
	})
	public List<T> getData() {
		return data;
	}

	public void setData(List<T> data) {
		this.data = data;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}
}