So the problem is rounding number without rounding, for example we have a number 5.789 and if we want to keep 2 decimal places so that number would be 5.78, it's bit difficult. Because we have to use round number and the value would be 5.79 after rounding.
Below is a code snippet to drop decimal places without rounding: |
public class NumberRounding { private static final DecimalFormat formatter = new DecimalFormat("#.####################"); public static BigDecimal roundingAtFixedPrecision(Number number, Integer precision) { String[] parts = null; try { parts = formatter.format(number).split("\\."); if (parts.length == 1) { return new BigDecimal(parts[0]); } return new BigDecimal(parts[0] + "." + (parts[1].length() > precision ? parts[1].substring(0, precision) : parts[1])); } finally { number = null; precision = null; parts = null; } } } |
And output should be as below: 678.789 converted to 678.78 -39.9899 converted to -39.98 33 converted to 33 -40 converted to -40 3.9 converted to 3.9 9.009 converted to 9.00 |
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Thursday, November 17, 2022
How to Drop Decimal Places Without Rounding, How to Round a Number to N Decimal Places in Java, Java – How to round double / float value to 2 decimal places, We can use DecimalFormat('0.00') or BigDecimal to round float / double to 2 decimal places.
Friday, October 28, 2022
Java - Always Name Your Thread Pools - Naming threads and thread-pools of ExecutorService - set name of thread
You could supply a ThreadFactory to newSingleThreadScheduledExecutor(ThreadFactory threadFactory). The factory will be responsibe for creating threads, and will be able to name them. |
ExecutorService is a JDK API that makes asynchronous task execution easier. ExecutorService offers a pool of threads and an easy-to-use API for assigning tasks. The ExecutorService gives the name of the threads in the thread pool. This shot discusses how we can assign custom names to the threads of the thread pool of the ExecutorService. |
BasicThreadFactory An ExecutorService employs a ThreadFactory to create its threads to execute tasks. In many circumstances, users do not need to worry about a ThreadFactory because the ExecutorService's default one will suffice. A custom ThreadFactory must be constructed with particular needs, such as thread naming. |
import java.util.TimerTask; import java.util.concurrent.*; public class Main { public static void main(String[] args) { // instant thread execution ExecutorService executorService = Executors.newFixedThreadPool(3, namedThreadFactory("test-thread")); for (int i=0; i < 5; i++) { executorService.submit(() -> System.out.println(Thread.currentThread().getName())); } executorService.shutdown(); // scheduled thread execution ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(namedThreadFactory("scheduled-thread")); TimerTask repeatedTask = new TimerTask() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()); } finally { executor.shutdownNow(); } } }; executor.schedule(repeatedTask, 1L, TimeUnit.MINUTES); } static ThreadFactory namedThreadFactory(String name) { return new YourThreadFactory(name); } } class YourThreadFactory implements ThreadFactory { private String name = "[No Name]"; YourThreadFactory(String name) { this.name = name; } public Thread newThread(Runnable r) { return new Thread(r, name); } } |
Thursday, July 12, 2018
Java > Convert text content to Image > Using Java Create An Image And Save To File With Transparent Background
For example, from the string Pritom K Mondal, I would like to generate this simple image: |
package com.pkm; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class TextToImage { public static void main(String[] args) { String text = "Pritom K Mondal"; BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); Font font = new Font("Arial", Font.PLAIN, 48); g2d.setFont(font); FontMetrics fm = g2d.getFontMetrics(); int width = fm.stringWidth(text) + 20; int height = fm.getHeight(); g2d.dispose(); img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); g2d = img.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2d.setFont(font); fm = g2d.getFontMetrics(); g2d.setColor(Color.BLACK); g2d.drawString(text, 10, fm.getAscent()); g2d.dispose(); try { ImageIO.write(img, "png", new File("Image.png")); } catch (IOException ex) { ex.printStackTrace(); } } } |
And output is like below: |
|
Grails on Groovy over Java > Email Address Validation Using Regex
Below is a sample code snippet to validate email address using REGEX |
package com.pkm; import java.util.regex.Pattern; public class EmailValidationRegex { private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+([\\.\\+]?[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private static Pattern _pattern = null; public static void main(String[] args) { check("pritomkucse+regex.test@gmail.com"); check("pkm@c.commmmmmmmmmmmmmmmmmmmm"); check("pkm@c.commmmmmmmmmmmmmmmmmmmm."); check("pkm.+invalid@no.valid"); } static void check(String email) { System.out.println(email + " > " + valid(email).toString().toUpperCase()); } static Boolean valid(String email) { return getPattern().matcher(email).matches(); } static Pattern getPattern() { if (_pattern != null) return _pattern; _pattern = Pattern.compile(EMAIL_PATTERN); return _pattern; } } |
Saturday, June 16, 2018
How to handle HTTP 403 forbidden error in Java
Sometimes when trying to connect to a web service using a java client, we may face a 403 forbidden HTTP response code, it is workable but in some reason the service is accessible normally from web browsers. |
The HTTP 403 forbidden error doesn’t necessarily occur due to missing authentication attributes or invalid authentication, some web services would only authorize web browsers or some specific clients to access them, while they deny any requests coming from third-party clients. And we are going to handle this situation. |
This problem is normally resolved by imitating the web browser request so that the web service deals with the java client as if it was a web browser. |
Below is a typical request logged from a browser: |
GET /feeds HTTP/1.1 Host: publicservice.com:443 Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Cookie: OGP=-4061129:; SID=FAYIU7tO.... Referer: https://clients5.google.com/pagead/drt/dn/ User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 X-Client-Data: CIa2yQEIpLbJAQjBtskBCKmdygEIqKPKARiSo8oB |
As noticed, the “User-Agent” header specifies the name and the type of the client which is trying to access the service, so in order to imitate the web browser we need to add this header to our request. Following is how to add it using HttpUrlConnection: |
String url = "https://xxx.com/yyy"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); |
Thursday, January 11, 2018
XERO Private Application | XERO Connect Using Private Application Java | Java to Connect to XERO Private Application
At first you have to create an Private Application in XERO. If you didn't yet you can follow the below link: Connect to Xero Private Application Using Php Application |
You already notified that there are two combinations of public/private key file. Public key need to create application and Private key need to sign data before send to XERO. Below is a sample Java script which will connect to XERO private application. |
package com.pkm; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedReader; import java.io.FileReader; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.KeyFactory; import java.security.Signature; import java.security.interfaces.RSAPrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import java.util.*; /** * Created by pritom on 2/01/2018. */ public class XeroPrivateApiUtils { private static final String NONCE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final String ORGANIZATION_URL = "https://api.xero.com/api.xro/2.0/Organisation"; private String sbs; private String path; private String method; private Map<Object, Object> configs = new HashMap<>(); private Map<Object, Object> params = new HashMap<>(); private Map<Object, Object> sign = new HashMap<>(); private String KEY_FILE = null; private String CONSUMER_KEY = null; private String CONSUMER_SECRET = null; public static void main(String[] args) throws Exception { XeroPrivateApiUtils xero = new XeroPrivateApiUtils(); HttpJavaClient.Response response = xero.execute("GET", XeroPrivateApiUtils.ORGANIZATION_URL, new HashMap(), new HashMap()); System.out.println(response.toString()); } private XeroPrivateApiUtils() { this.KEY_FILE = "private.key"; this.CONSUMER_KEY = "IKAEAI8BA..........1MAOR9XBEHU"; this.CONSUMER_SECRET = "STXPEDM..........0FWMPLIDGB6DS"; putToMap(this.configs, "consumer_key", CONSUMER_KEY); putToMap(this.configs, "consumer_secret", CONSUMER_SECRET); putToMap(this.configs, "core_version", "2.0"); putToMap(this.configs, "payroll_version", "1.0"); putToMap(this.configs, "file_version", "1.0"); putToMap(this.configs, "application_type", "Private"); } HttpJavaClient.Response execute( String method, String path, Map<Object, Object> configs, Map<Object, Object> params ) throws Exception { this.method = method; this.path = path; this.params = params; putToMap(this.configs, configs); this.buildParameters(); this.sign(); Map<Object, Object> headers = new HashMap<>(); putToMap(headers, "Accept", "application/json"); if (this.method.equalsIgnoreCase("get")) { return HttpJavaClient.doGet((String) this.sign.get("signed_url"), headers); } return null; } private void sign() throws Exception { putToMap(this.params, "oauth_signature", this.generateSignature()); putToMap(this.sign, "parameters", this.params); putToMap(this.sign, "signature", escape((String) this.params.get("oauth_signature"))); putToMap(this.sign, "signed_url", this.path + "?" + normalizeParameters(true)); putToMap(this.sign, "sbs", this.sbs); } private String generateSignature() throws Exception { switch ((String) this.params.get("oauth_signature_method")) { case "RSA-SHA1": this.sbs = escape(this.method.toUpperCase()); this.sbs += "&" + escape(this.path); this.sbs += "&" + escape(this.normalizeParameters(false)); RSAPrivateKey privateKey = getPrivateKey(KEY_FILE); Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(privateKey); sign.update(this.sbs.getBytes("UTF-8")); return encodeBase64(sign.sign()); case "HMAC-SHA1": String secret = this.configs.get("consumer_secret") + "&"; if (this.configs.get("access_token_secret") != null) { secret = secret + this.configs.get("access_token_secret"); } this.sbs = escape(this.method.toUpperCase()); this.sbs += "&" + escape(this.path); this.sbs += "&" + escape(this.normalizeParameters(false)); return hmacSha(secret, this.sbs); default: throw new Exception("Undefined signature method"); } } private static String hmacSha(String key, String value) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] result = mac.doFinal(value.getBytes()); return encodeBase64(result); } public static String encodeBase64(String o) { BASE64Encoder base64Encoder = new BASE64Encoder(); return base64Encoder.encodeBuffer(o.getBytes()).replace("\r\n", "").replace("\n", ""); } private static String encodeBase64(byte[] o) { BASE64Encoder base64Encoder = new BASE64Encoder(); return base64Encoder.encodeBuffer(o).replace("\r\n", "").replace("\n", ""); } private static RSAPrivateKey getPrivateKey(String fileName) throws Exception { byte[] encoded = decodeBase64(getKey(fileName)); KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); return (RSAPrivateKey) kf.generatePrivate(keySpec); } private static byte[] decodeBase64(String o) throws Exception { BASE64Decoder decoder = new BASE64Decoder(); return decoder.decodeBuffer(o); } private String normalizeParameters(Boolean filter) throws Exception { String normalized = ""; for (Object o : this.params.entrySet()) { Map.Entry me2 = (Map.Entry) o; String key = me2.getKey().toString(); Object value = me2.getValue(); Boolean allow = !(key.equalsIgnoreCase("xml") && filter) && !key.endsWith("_secret"); if (allow) { normalized += escape(key) + "=" + escape(value.toString()) + "&"; } } return normalized.length() > 0 ? normalized.substring(0, normalized.length() - 1) : normalized; } private static String escape(String context) throws Exception { context = rawUrlEncode(context); context = stringReplace("+", "%20", context); context = stringReplace("!", "%21", context); context = stringReplace("*", "%2A", context); context = stringReplace("\'", "%27", context); context = stringReplace("(", "%28", context); context = stringReplace(")", "%29", context); return context; } private static String rawUrlEncode(String context) throws Exception { return URLEncoder.encode(context, "UTF-8"); } private static String rawUrlDecode(String context) throws Exception { return URLDecoder.decode(context, "UTF-8"); } private static String stringReplace(String search, String fill, String context) { return context.replace(search, fill); } private void buildParameters() { putToMap(this.params, "oauth_nonce", shuffle(5)); putToMap(this.params, "oauth_token", CONSUMER_KEY); putToMap(this.params, "oauth_version", "1.0"); putToMap(this.params, "oauth_timestamp", "" + ((System.currentTimeMillis()) / 1000)); putToMap(this.params, "oauth_consumer_key", CONSUMER_KEY); putToMap(this.params, "oauth_signature_method", "RSA-SHA1"); this.params = new TreeMap(this.params); //Sorted map by key } private static String shuffle(Integer length) { List<Character> characters = new ArrayList<Character>(); for(char c : NONCE.toCharArray()){ characters.add(c); } StringBuilder output = new StringBuilder(length); while(length != 0) { int randPicker = (int) (Math.random() * characters.size()); output.append(characters.get(randPicker)); length --; } return output.toString(); } private static String getKey(String filename) throws Exception { String key = ""; BufferedReader br = new BufferedReader(new FileReader(filename)); String line; while ((line = br.readLine()) != null) { if (!line.startsWith("-")) { key += line + "\n"; } } br.close(); return key; } private static void putToMap(Map<Object, Object> map, Map fromMap) { for (Object key : fromMap.keySet().toArray()) { putToMap(map, key.toString(), fromMap.get(key)); } } private static void putToMap(Map<Object, Object> map, Object key, Object value) { map.put(key, value); } private static void println(Object o) { System.out.println("" + o); } private static void exception() throws Exception { throw new Exception(); } } |
You can download a sample Private Key File from this link |
And output? Obviously as below: |
{ "Id": "966aed9c-....-4d86-....-c59a6b34eb2c", "Status": "OK", "ProviderName": "Dev Private", "DateTimeUTC": "\/Date(1515683933534)\/", "Organisations": [ { "APIKey": "WXP9HDM..........ILMSZHZIUSIA5", "Name": "Dev Organisation", "LegalName": "Dev Organisation", "PaysTax": true, "Version": "AU", "OrganisationType": "COMPANY", "BaseCurrency": "AUD", "CountryCode": "AU", "IsDemoCompany": false, "OrganisationStatus": "ACTIVE", "FinancialYearEndDay": 30, "FinancialYearEndMonth": 6, "SalesTaxBasis": "ACCRUALS", "SalesTaxPeriod": "QUARTERLY1", "DefaultSalesTax": "Tax Exclusive", "DefaultPurchasesTax": "Tax Inclusive", "CreatedDateUTC": "\/Date(1514794572000)\/", "OrganisationEntityType": "COMPANY", "Timezone": "AUSEASTERNSTANDARDTIME", "ShortCode": "!wnfkR", "OrganisationID": "91de7ce4-....-48e8-....-74573ab8b4e0", "LineOfBusiness": "tests xero integration", "Addresses": [], "Phones": [], "ExternalLinks": [], "PaymentTerms": {} } ] } |
Subscribe to:
Posts (Atom)