parse Json data with array using java - java

i use gson to get parese json data.but i have some problems
here is my json url data https://api.kcg.gov.tw/api/service/get/2c1d9959-d038-4918-bae3-409680f8193a
you can see that the json data have structure.
here is my code first
package iii_project;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class GsonFetchNetworkJson2 {
public class ItemType {
int seq;
String 資料年度;
String 統計項目;
String 稅目別;
String 資料單位;
String 值;
// public String toString() {
// return Arrays.toString(seq);
// }
}
public class Item {
String isImage;
String success;
String id;
ItemType[] data;
#Override
public String toString() {
return "Item [isImage=" + isImage + ", success=" + success + ", data=" + Arrays.toString(data) + "]";
}
}
public static void main(String[] ignored) throws Exception {
// Type listType = new TypeToken<List<Item>>() {}.getType();
URL url = new URL("https://api.kcg.gov.tw/api/service/get/2c1d9959-d038-4918-bae3-409680f8193a");
InputStreamReader reader = new InputStreamReader(url.openStream());
Item dto = new Gson().fromJson(reader, Item.class);
System.out.println(dto);
// System.out.println(dto.isImage);
// System.out.println(dto.id);
// System.out.println(dto.success);
// System.out.println(dto.types);
// System.out.println(dto.data.toString());
// System.out.println(dto.toString());
// System.out.println(Arrays.toString(dto.date));
// Detail abd = new Gson().fromJson(reader, Detail.class);
// System.out.println(Arrays.toString(abd.值));
// System.out.println(abd.資料單位);
// System.out.println(Arrays.toString(dto.data));
}
}
but the result of
System.out.println(dto);
i haved override it but still can not work
i want the data like this:
here is the answer!!!!
package iii_project;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class GsonFetchNetworkJson2 {
public class ItemType {
private int seq;
private String 資料年度;
private String 統計項目;
private String 稅目別;
private String 資料單位;
private String 值;
//getter and setter
#Override
public String toString() {
return "ItemType [seq=" + seq + ", 資料年度=" + 資料年度 + ", 統計項目=" + 統計項目 + ", 稅目別=" + 稅目別 + ", 資料單位=" + 資料單位
+ ", 值=" + 值 + "]";
}
}
public class Item {
String isImage;
String success;
String id;
ItemType[] data;
#Override
public String toString() {
return "Item [isImage=" + isImage + ", success=" + success + ", id=" + id + ", data="
+ Arrays.toString(data) + "]";
}
}
public static void main(String[] ignored) throws Exception {
// Type listType = new TypeToken<List<Item>>() {}.getType();
URL url = new URL("https://api.kcg.gov.tw/api/service/get/2c1d9959-d038-4918-bae3-409680f8193a");
InputStreamReader reader = new InputStreamReader(url.openStream());
Item dto = new Gson().fromJson(reader, Item.class);
// System.out.println(dto);
// System.out.println(Arrays.toString(dto.data));
System.out.println(dto.isImage);
System.out.println(dto);
// for(ItemType element : dto.data) {
// System.out.println(element);
// }
// System.out.println(dto.data);
// System.out.println(dto.id);
// System.out.println(dto.success);
// System.out.println(dto.types);
// System.out.println(dto.data.toString());
// System.out.println(dto.toString());
// System.out.println(Arrays.toString(dto.date));
// Detail abd = new Gson().fromJson(reader, Detail.class);
// System.out.println(Arrays.toString(abd.值));
// System.out.println(abd.資料單位);
// System.out.println(Arrays.toString(dto.data));
}
}

Your dto.data is array, so your current output is the address of that array.
Replace your System.out.println(dto.data) by System.out.println(Arrays.toString(array)); to print your data array
Check out this to have more details: What's the simplest way to print a Java array?

You need to override the toString function in your Detail class, otherwise it will only print out its address for the object.

but still can not work
It works exactly as you've written it to!
I want the data like this (shows image of some JSON object)
You need to explicitly write the indentation in your toString function, then
For example
public String toString() {
StringBuilder sb = new StringBuilder("{\n");
sb.append(" \"isImage\":" + isImage).append(",\n");
sb.append(" \"data\":");
if (data.length == 0) {
// add empty array string "[]"
} else {
sb.append("[");
for (ItemType it : data) {
// create object string
// append to outer builder
// add a comma, but not for the very last object in the array
}
sb.append("]");
}
// TODO: close off remaining end brackets
return sb.toString();
}
And your ItemType class still needs it's own toString...
If you really just want to print indented JSON without much code, then don't try to print an Item class
Pretty-Print JSON in Java

Related

Get controller name and java service path in controller advice

Hi All i have created a global exception handler in my spring boot app and writing the exception occurred in AWS cloudwatch below code working fine i am able to write the exception in cloudwatch but the challenge is i am unable to get the Restcontroller name and service path from where the the particular exception happened.
Sample java service
#GetMapping(value = "DynamoDb/deleteTable")
public String deleteTable(#RequestParam String TableName) throws InterruptedException {
Table table = dynamoDB.getTable(TableName);
try {
table.delete();
table.waitForDelete();
} catch (Exception e) {
throw e;
}
return "Success";
}
When ever exception occurred it control transferred to controlleradvice global exception handler
Here is my code
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent;
import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest;
import java.util.Arrays;
#ControllerAdvice
public class ExceptionControllerAdvice {
#ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
ErrorResponse error = new ErrorResponse();
error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
error.setMessage(ex.getMessage());
error.setController(ex.getMessage());
error.setService(ex.getMessage());
error.setTimestamp(System.currentTimeMillis());
PutLogEvents(error);
return new ResponseEntity<ErrorResponse>(error, HttpStatus.OK);
}
public static void PutLogEvents(ErrorResponse Er)
{
String regionId = "us-east-1";
String logGroupName = "xxxxxxx";
String logStreamName = "xxxxxxx";
CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder().region(Region.of(regionId)).build();
// A sequence token is required to put a log event in an existing stream.
// Look up the stream to find its sequence token.
String sequenceToken = getNextSequenceToken(logsClient, logGroupName, logStreamName);
// Build a JSON log using the EmbeddedMetricFormat.
String message = "[{" +
" \"Timestamp\": " + Er.getTimestamp() + "," +
" \"ErrorCode\": " + Er.getErrorCode() + "," +
" \"ControllerName\": " + Er.getErrorCode() + "," +
" \"ServiceName\": " + Er.getErrorCode() + "," +
" \"ErrorMsg\": " + Er.getErrorCode() + "" +
"}]";
InputLogEvent inputLogEvent = InputLogEvent.builder()
.message(message)
.timestamp(Er.getTimestamp())
.build();
// Specify the request parameters.
PutLogEventsRequest putLogEventsRequest = PutLogEventsRequest.builder()
.logEvents(Arrays.asList(inputLogEvent))
.logGroupName(logGroupName)
.logStreamName(logStreamName)
// Sequence token is required so that the log can be written to the
// latest location in the stream.
.sequenceToken(sequenceToken)
.build();
logsClient.putLogEvents(putLogEventsRequest);
}
private static String getNextSequenceToken(CloudWatchLogsClient logsClient, String logGroupName, String logStreamName) {
DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder()
.logGroupName(logGroupName)
.logStreamNamePrefix(logStreamName)
.build();
DescribeLogStreamsResponse describeLogStreamsResponse = logsClient.describeLogStreams(logStreamRequest);
// Assume that a single stream is returned since a specific stream name was
// specified in the previous request.
return describeLogStreamsResponse.logStreams().get(0).uploadSequenceToken();
}
}
Errorresponse.class
public class ErrorResponse {
private int errorCode;
private String message;
private String Controller;
private String Service;
private String ProjectName;
private long Timestamp;
public ErrorResponse(int errorCode, String message, String controller, String service, String projectName, long timestamp) {
this.errorCode = errorCode;
this.message = message;
Controller = controller;
Service = service;
ProjectName = projectName;
Timestamp = timestamp;
}
public ErrorResponse() {
}
#Override
public String toString() {
return "ErrorResponse{" +
"errorCode=" + errorCode +
", message='" + message + '\'' +
", Controller='" + Controller + '\'' +
", Service='" + Service + '\'' +
", ProjectName='" + ProjectName + '\'' +
", Timestamp=" + Timestamp +
'}';
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getController() {
return Controller;
}
public void setController(String controller) {
Controller = controller;
}
public String getService() {
return Service;
}
public void setService(String service) {
Service = service;
}
public String getProjectName() {
return ProjectName;
}
public void setProjectName(String projectName) {
ProjectName = projectName;
}
public long getTimestamp() {
return Timestamp;
}
public void setTimestamp(long timestamp) {
Timestamp = timestamp;
}
}
Could any one please help me how can i get the Restcontroller name and service path in Global exception handler?
Hi All Thanks to all by using below code i am able to get the result as suggested by client. Hope this may help some one. Thanks
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent;
import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
#ControllerAdvice
public class ExceptionControllerAdvice {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
#Value("${application.name}")
private String applicationName;
#Value("${aws.logGroupName}")
private String logGroupName;
#Value("${aws.logStreamName}")
private String logStreamName;
#ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex, HandlerMethod handlerMethod, HttpServletRequest request) throws JsonProcessingException {
Class ControllerName = handlerMethod.getMethod().getDeclaringClass();
String MethodName = handlerMethod.getMethod().getName();
ErrorResponse error = new ErrorResponse();
error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
error.setErrorMessage(ex.getMessage());
error.setControllerName(ControllerName.toString());
error.setServiceName(MethodName.toString());
error.setTimeStamp(sdf.format(System.currentTimeMillis()));
error.setProjectName(applicationName);
error.setServicePath(request.getRequestURL().toString());
PutLogEvents(error);
return new ResponseEntity<ErrorResponse>(error, HttpStatus.OK);
}
public void PutLogEvents(ErrorResponse Er) throws JsonProcessingException {
String regionId = "xxxxx";
String logGroupName = "xxxxx";
String logStreamName = "xxxxx";
CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder().region(Region.of(regionId)).build();
// A sequence token is required to put a log event in an existing stream.
// Look up the stream to find its sequence token.
String sequenceToken = getNextSequenceToken(logsClient, logGroupName, logStreamName);
// Build a JSON log using the EmbeddedMetricFormat.
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(Er);
String message =json;
InputLogEvent inputLogEvent = InputLogEvent.builder()
.message(message)
.timestamp(System.currentTimeMillis())
.build();
// Specify the request parameters.
PutLogEventsRequest putLogEventsRequest = PutLogEventsRequest.builder()
.logEvents(Arrays.asList(inputLogEvent))
.logGroupName(logGroupName)
.logStreamName(logStreamName)
// Sequence token is required so that the log can be written to the
// latest location in the stream.
.sequenceToken(sequenceToken)
.build();
logsClient.putLogEvents(putLogEventsRequest);
}
private static String getNextSequenceToken(CloudWatchLogsClient logsClient, String logGroupName, String logStreamName) {
DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder()
.logGroupName(logGroupName)
.logStreamNamePrefix(logStreamName)
.build();
DescribeLogStreamsResponse describeLogStreamsResponse = logsClient.describeLogStreams(logStreamRequest);
// Assume that a single stream is returned since a specific stream name was
// specified in the previous request.
return describeLogStreamsResponse.logStreams().get(0).uploadSequenceToken();
}
}
Result should be like this
{
"errorMessage": "Table already exists: ProductFgh (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ResourceInUseException; Request ID: 6S14VS0E6ESUMG55DL937IC42JVV4KQNSO5AEMVJF66Q9ASUAAJG)",
"timeStamp": "2020-Jan-22 11:53:58",
"errorCode": 500,
"projectName": "DynamoDB",
"servicePath": "http://localhost:8090/DynamoDb/createTable",
"controllerName": "class com.example.DynamoDB.DynamoDBController",
"serviceName": "createExampleTable"
}
As of now i have achieved this through above code if any better approach is available let me know. Thanks to all
You can get the class name from which the exception was thrown as follows:
ex.getStackTrace()[0].getClassName();

GSON not saving new fields to file

I'm adding new fields to my data class, they're not saving to file. None of the fields are transient.
I'm loading the file with GSON then resaving it to try to save new fields. I've tried setting the fields in the constructor and just setting them on creation. Neither worked, I also tried saving the file in the traditional way using GSON, that didn't work either. Modifying already existing fields works and they save properly, but new fields are never created.
private void loadUserData(Player player) {
File userFile = new File(userFolder + File.separator + player.getUniqueId().toString() + ".json");
try {
if (!userFile.exists()) {
User user = new User(player.getUniqueId(), player.getName(), player.isOp() ? "§8(§9Manager§8) §9" : "§7", "");
FileUtils.writeStringToFile(userFile, new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(user), StandardCharsets.UTF_8.name());
userCache.put(player.getUniqueId(), user);
} else {
User user = new GsonBuilder().create().fromJson(new FileReader(userFile), User.class);
user.save();
if(!userCache.containsKey(player.getUniqueId())) {
userCache.put(player.getUniqueId(), user);
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
public void save() {
File userFolder = new File(Core.getInstance().getModuleManager().getModuleInstance(SMPModule.class).getDataFolder() + File.separator + "users");
try {
FileUtils.writeStringToFile(new File( userFolder + File.separator + uuid.toString() + ".json"),
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(this), StandardCharsets.UTF_8.name());
} catch (IOException e) {
e.printStackTrace();
}
}
Data Class:
package net.astreul.core.module.impl.SMP.user;
import com.google.common.collect.Lists;
import com.google.gson.GsonBuilder;
import lombok.AccessLevel;
import lombok.Setter;
import net.astreul.core.Core;
import net.astreul.core.module.impl.SMP.SMPModule;
import net.astreul.core.module.impl.SMP.cosmetic.CosmeticPackage;
import net.astreul.core.util.Format;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
#Setter
public class User {
#Setter(AccessLevel.NONE) private UUID uuid;
private String nickname;
private String prefix;
private String suffix;
private long lastLogin;
private List<CosmeticPackage> ownedCosmetics;
private List<String> ownedTags;
private String activeTag;
public User(UUID uuid, String nickname, String prefix, String suffix) {
this.uuid = uuid;
this.nickname = nickname;
this.prefix = prefix;
this.suffix = suffix;
lastLogin = System.currentTimeMillis();
ownedCosmetics = Lists.newArrayList();
ownedTags = Lists.newArrayList();
this.activeTag = "";
}
public void save() {
File userFolder = new File(Core.getInstance().getModuleManager().getModuleInstance(SMPModule.class).getDataFolder() + File.separator + "users");
try {
FileUtils.writeStringToFile(new File( userFolder + File.separator + uuid.toString() + ".json"),
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(this));
} catch (IOException e) {
e.printStackTrace();
}
}
public File getFile() {
File userFolder = new File(Core.getInstance().getModuleManager().getModuleInstance(SMPModule.class).getDataFolder() + File.separator + "users");
return new File( userFolder + File.separator + uuid.toString() + ".json");
}
public String getNickname() {
return Format.color(nickname);
}
public String getPrefix() {
return Format.color(prefix);
}
public String getSuffix() {
return Format.color(suffix);
}
public long getLastLogin() {
return lastLogin;
}
public boolean hasPackage(CosmeticPackage cosmeticPackage) {
return ownedCosmetics.contains(cosmeticPackage);
}
public List<CosmeticPackage> getOwnedCosmetics() {
return ownedCosmetics;
}
public List<String> getOwnedTags() {
return ownedTags;
}
public String getActiveTag() {
return activeTag;
}
}
I expected it to save the new fields to file, but it didn't save anything at all. There was no error at all.
I think the problem here is related to how gson creates instances.
If you look at the source code of gson you'll find that it tries to create the object instances using one of 3 things. First it tries instance creators - entities that know how to create an object. You can register one yourself to create the user - check here
If there's none it'll check for default constructors, which you don't have. A default constructor is one that has no arguments.
The last step is a best effort to create the object and it uses Java's unsafe. As the name suggests this is unsafe to do and the reason is because it bypasses all constructors. In your case, it'll bypass any initialization you have put inside the constructor and will leave the fields that are not in the json as null.
If you don't change the fields externally, once you save the user object, the new fields are still null and hence not saved.
To fix this, you can provide an instance creator, or initialize the fields from another method or somehow provide a default constructor.

java replace in files with auto increment

I've been looking for easy way to add ID to HTML tags and spent few hours here jumping form one tool to another before I came up with this little test solving my issues. Hence my sprint backlog is almost empty I have some time to share. Feel free to make it clear and enjoy those whom are asked by QA to add the ID. Just change the tag, path and run :)
Had some issue here to make proper lambda due to lack of coffee today...
how to replace first occurence only, in single lambda? in files I had many lines having same tags.
private void replace(String path, String replace, String replaceWith) {
try (Stream<String> lines = Files.lines(Paths.get(path))) {
List<String> replaced = lines
.map(line -> line.replace(replace, replaceWith))
.collect(Collectors.toList());
Files.write(Paths.get(path), replaced);
} catch (IOException e) {
e.printStackTrace();
}
}
Above was replacing all lines as it found text to replace in next lines. Proper matcher with repleace that has autoincrement would be better to use within this method body isntead of preparing the replaceWith value before the call. If I'll ever need this again I'll add you another final version .
Final version to not waste more time (phase green):
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
#RunWith(MockitoJUnitRunner.class)
public class RepalceInFilesWithAutoIncrement {
private int incremented = 100;
/**
* The tag you would like to add Id to
* */
private static final String tag = "label";
/**
* Regex to find the tag
* */
private static final Pattern TAG_REGEX = Pattern.compile("<" + tag + " (.+?)/>", Pattern.DOTALL);
private static final Pattern ID_REGEX = Pattern.compile("id=", Pattern.DOTALL);
#Test
public void replaceInFiles() throws IOException {
String nextId = " id=\"" + tag + "_%s\" ";
String path = "C:\\YourPath";
try (Stream<Path> paths = Files.walk(Paths.get(path))) {
paths.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
try {
List<String> foundInFiles = getTagValues(readFile(filePath.toAbsolutePath().toString()));
if (!foundInFiles.isEmpty()) {
for (String tagEl : foundInFiles) {
incremented++;
String id = String.format(nextId, incremented);
String replace = tagEl.split("\\r?\\n")[0];
replace = replace.replace("<" + tag, "<" + tag + id);
replace(filePath.toAbsolutePath().toString(), tagEl.split("\\r?\\n")[0], replace, false);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
System.out.println(String.format("Finished with (%s) changes", incremented - 100));
}
private String readFile(String path)
throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, StandardCharsets.UTF_8);
}
private List<String> getTagValues(final String str) {
final List<String> tagValues = new ArrayList<>();
final Matcher matcher = TAG_REGEX.matcher(str);
while (matcher.find()) {
if (!ID_REGEX.matcher(matcher.group()).find())
tagValues.add(matcher.group());
}
return tagValues;
}
private void replace(String path, String replace, String replaceWith, boolean log) {
if (log) {
System.out.println("path = [" + path + "], replace = [" + replace + "], replaceWith = [" + replaceWith + "], log = [" + log + "]");
}
try (Stream<String> lines = Files.lines(Paths.get(path))) {
List<String> replaced = new ArrayList<>();
boolean alreadyReplaced = false;
for (String line : lines.collect(Collectors.toList())) {
if (line.contains(replace) && !alreadyReplaced) {
line = line.replace(replace, replaceWith);
alreadyReplaced = true;
}
replaced.add(line);
}
Files.write(Paths.get(path), replaced);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try it with Jsoup.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JsoupTest {
public static void main(String argv[]) {
String html = "<html><head><title>Try it with Jsoup</title></head>"
+ "<body><p>P first</p><p>P second</p><p>P third</p></body></html>";
Document doc = Jsoup.parse(html);
Elements ps = doc.select("p"); // The tag you would like to add Id to
int i = 12;
for(Element p : ps){
p.attr("id",String.valueOf(i));
i++;
}
System.out.println(doc.toString());
}
}

Unable to get Integer Value of Variable Stored in Java Thread Local Object

I am trying to get the integer value of a Thread Local Object as in the code below, but it keeps throwing an error. However, when I try to display it as a string, it displays.
My Question: How can I achieve extracting the Integer value?
Note: Parsing the string as in the code below doesn't work
package ids;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Random;
import javax.swing.SwingWorker;
import jpcap.*;
import jpcap.packet.Packet;
public class InterfaceThread implements Runnable {
ThreadLocal MyInterfaceNumber = new ThreadLocal();
InterfaceThread() {
}
InterfaceThread(int InterfaceNumber) {
MyInterfaceNumber.set(InterfaceNumber);
System.out.println("Check: " + MyInterfaceNumber.get());
}
#Override
public void run() {
String IntNum = (String) MyInterfaceNumber.get();
int InterfaceToPrint = Integer.parseInt(IntNum);
System.out.println("Interface: " + InterfaceToPrint);
Messages msg = new Messages();
Printer print = new Printer();
try {
//Open Selected Interface
JpcapCaptor captor = JpcapCaptor.openDevice(IDS.Interfaces[InterfaceToPrint], 65535, true, 5000);
System.out.println("Interface Dlink Name: " + IDS.Interfaces[InterfaceToPrint].description);
// print.TextAreaAppend("Traffic on Interface "+InterfaceToPrint+" Now Being Sniffed\n");
while (MainFrame.StopSniffing == false) {
captor.processPacket(-1, new Printer());
}
//captor.loopPacket(-1, new Printer());
captor.close();
} catch (IOException ex) {
msg.ErrorMessages("Interface " + InterfaceToPrint + " Encountered Error: " + ex);
}
}
public void Start(int InterfaceNumber) {
InterfaceThread interfaceT = new InterfaceThread(InterfaceNumber);
Thread thread = new Thread(interfaceT);
thread.start();
}
}
I suggest you use generics to simplify the code
private final ThreadLocal<Integer> int = new ThreadLocal<>();
// to read
Integer i = int.get();
// to write
int.set(i);

Keep getting null pointer exception

here is my program: basically i have an xml file and from that file i have to decode a base64 string but i keep getting NullPointerException..please help! code is as follows...
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.commons.codec.binary.Base64;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Arrays;
public class main {
public static void main(String[] args) throws Exception {
SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandler handler = new SAXHandler();
//parser.parse(ClassLoader.getSystemResourceAsStream("ATMSPopulateDMSData.xml"),
// handler);
parser.parse(new FileInputStream("C:\\Users\\qta6754\\workspace\\Java_Dev\\XML64_Decoded\\ATMSMessageData.xml"), handler);
for (NeededInfo emp : handler.empList) {
System.out.println(emp);
}
}
}
class SAXHandler extends DefaultHandler {
List<NeededInfo> empList = new ArrayList<>();
NeededInfo emp = null;
String content = null;
String did = null;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (qName) {
case "dMSDeviceStatus":
emp = new NeededInfo();
emp.id = attributes.getValue("id");
emp.Read();
break;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
content = String.copyValueOf(ch, start, length).trim();
}
}
class NeededInfo {
String id;
String firstName;
String lastName;
String location;
String organization_id;
String operator_id;
String device_id;
String dms_device_status;
String dms_current_message;
String last_comm_time;
String date;
String time;
public String toString() {
//return firstName + " " + lastName + "(" + id + ")" + location+date+time+device_name;
return "Organization id: " + organization_id + "\n" + "Operator id: " + operator_id + "\n" + "Device id: " + device_id + "\n"
+ "Dms Device Status: " + dms_device_status + "\n" + "Dms Current Message: " + dms_current_message + "\n" + "Last Comm Time" + "\n"
+ "Time: " + time + "\n" + "Date: " + date + "\n" + "decoded string is: " + "\n" + "-------------------------------------";
}
public void Read() {
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());
String decodedString = new String(byteArray);
System.out.print("The decoded message is: " + decodedString);
// return decodedString;
}
}
It's hard to guess where you're getting your error, but I'm assuming here:
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());
I don't see dms_current_message being initialized ever, yet you're calling a method on it, which would definitely result in the null pointer exception.
Your Read method accesses the dms_current_message which is never initialized in all the code you included in your question.
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());

Categories

Resources