Java code snippets – utils – tips

//Java code snippets – utils – tips

How to make an empty PUT request in JAVA

public static HttpURLConnection put(String endpoint, String token) {
HttpURLConnection con = null;
try {
URL url = new URL(endpoint);
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", "Bearer " + token);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("User-Agent", <em>USER_AGENT</em>);
con.setRequestProperty("Content-Length" , "0");
con.setRequestMethod("PUT");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes("");
out.flush();
} catch (Exception e) {
Logger.<em>log</em>(e);
}
return con;
}

If the Content-Length is not specified the server will return a 411 status code error.

HTTP Status Code 411 (Length Required) is sent by the server as a response when it refuses to accept a message without a content-length header, for whatever reason.

The DataOutputStream is still required even if you send an empty payload.

Java find project location

public static String findProjectLocation() {
String path = "";
try {
path = new File(".").getCanonicalPath();
} catch (IOException e) {
Logger.<em>log</em>(e);
}
System.<em>setProperty</em>("app.home", path);
return path;
}

How to build a jar with dependencies included using Maven

<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<mainClass>xyz.adrianweb.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>

Then run this maven command  : package

How to write logs in Java using log4j

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1, FILE

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# Define the file appender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender

# Set the name of the file
log4j.appender.FILE.File=logs.log

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, should not overwrite
log4j.appender.FILE.Append=true

# Set the maximum file size before rollover
log4j.appender.FILE.MaxFileSize=1MB

# Set the the backup index
log4j.appender.FILE.MaxBackupIndex=2

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n

How to encrypt/decrypt with 256 bit in JAVA

Java Cryptography Extension (JCE) Unlimited Strength is needed. Without it the maximum key size are limited to 128-bit. You may get this error : java.security.InvalidKeyException: Illegal key size

To avoid this, in Java 8 you must download : http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html and add the files in C:/Program Files/Java/jre<version>/lib/security/

Java 9 enables unlimited encryption by default.

How to read from Windows Registry using Java

public static String readRegistry(String location, String key) {
String result = "";
try {
Process process = Runtime.<em>getRuntime</em>().exec("reg query " + '"' + location + "\" /v " + key);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String[] parsed = reader.getResult().split("\\s+");
if (parsed.length > 1) {
result =  parsed[parsed.length - 1];
}
} catch (InterruptedException | IOException e) {
Logger.<em>log</em>(e);
}
return result;
}

Key Promoter X – Learn every shortcut for IntelliJ

Or MouseFeed for Eclipse

Shows the user the keyboard short-cuts when a button is pressed with the mouse. This provides an easy way to learn how to replace tedious mouse work with keyboard keys and helps to transition to a faster, mouse free development. Currently, it supports toolbar buttons, menu buttons, and tool windows and the actions therein.

https://plugins.jetbrains.com/plugin/9792-key-promoter-x

https://github.com/halirutan/IntelliJ-Key-Promoter-X

https://marketplace.eclipse.org/content/mousefeed

 

Get computer name in Java

public static String getComputerName() {
String computerName = System.<em>getenv</em>("COMPUTERNAME");
if (computerName == null || computerName.isEmpty()) {
try {
computerName = InetAddress.<em>getLocalHost</em>().getHostName();
Constants.<em>computerName </em>= computerName;
} catch (UnknownHostException e) {
Logger.<em>log</em>(e);
Logger.<em>message</em>("Cannot get the computer name");
}
}
if (computerName != null && !computerName.isEmpty()) {
computerName = computerName.split("\\.")[0];
}
return computerName;
}



<strong>Jackson deserialize array of objects in Java</strong>



public static List<Car> getCars(String response) {
List<Car> carList = new ArrayList<>();
try {
carList = Arrays.<em>asList</em>(ObjectBuilders.<em>getObjectMapper</em>().readValue(response, Car[].class));
} catch (Exception e) {
Logger.<em>log</em>(e);
}
return carList;
}

If you have a jsonArray response, then you must provide a Car[].class type

Some json utils :

public static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}

public static ObjectMapper getObjectMapper() {
if (<em>objectMapper </em>== null) {
<em>objectMapper </em>= new ObjectMapper();
<em>objectMapper</em>.enable(SerializationFeature.<em>INDENT_OUTPUT</em>);
}
return <em>objectMapper</em>;
}

Logger in Java - slf4j.Logger

public class Logger {

private Logger(){}
private static org.slf4j.Logger <em>logger </em>= LoggerFactory.<em>getLogger</em>(Logger.class);

public static void log(Exception e) {
<em>logger</em>.error(e.getLocalizedMessage() + e.getMessage());
StackTraceElement[] elements = e.getStackTrace();
for (int i = 1; i < elements.length; i++) {
StackTraceElement s = elements[i];
<em>logger</em>.error("\tat " + s.getClassName() + "." + s.getMethodName()
+ "(" + s.getFileName() + ":" + s.getLineNumber() + ")");
}
}

}

By |2018-07-27T18:55:52+00:00July 27th, 2018|0 Comments

Leave A Comment