I am trying to run a class inside a jar file. Inside the java program, I have a class called CustomSearchHandler which is calling a function to read an array of strings from a JSON file called Attributes.json. Note that this JSON file is in the same directory as the class.
public class CustomSearchHandler extends SearchHandler {
private static Logger logger = LoggerFactory.getLogger(CustomSearchHandler.class);
public static final String CURRENCYCODEHEADER = "currencycode";
#Override
public void handleRequestBody(SolrQueryRequest solrRequest,
SolrQueryResponse solrResponse) throws Exception {
ArrayList<String> fixedAttributesList = fetchAttributes("fixed_attributes");
}
public static ArrayList<String> fetchAttributes(String type){
ArrayList<String> attributesList = new ArrayList<String>();
try{
InputStream inputStream = CustomSearchHandler.class.getResourceAsStream("Attributes.json");
JSONObject json = new JSONObject(new InputStreamReader(inputStream));
JSONArray jsonArray = json.getJSONArray("fixed_attributes");
for (int i = 0; i < jsonArray.length(); i++) {
attributesList.add(jsonArray.getString(i));
}
logger.info("e");
} catch (Exception e) {
e.printStackTrace();
}
return attributesList;
}
}
When I create a jar from this and execute this, I get -
java.lang.NullPointerException
at java.base/java.io.Reader.<init>(Reader.java:167)
at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at CustomSearchHandler.fetchAttributes(CustomSearchHandler.java:125)
at CustomSearchHandler.handleRequestBody(CustomSearchHandler.java:60)
I just need to read the list of strings of array "fixed_attributes" and assign it to an ArrayList. Please help.
Related
I am building a Java app in JSF that makes a request to an API gets a JSON and fills a table with the JSON info...
This is the code:
#ManagedBean(name = "logic", eager = true)
#SessionScoped
public class Logic {
static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;
public void connect() {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("xxx");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
sb.append(inputLine+"\n");
in.close();
}
}catch(Exception e) {System.out.println(e);}
try {
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
jo = (JSONObject) cat.get(0);
jo.get("cif");
System.out.println(jo.get("cif"));
}catch(Exception e){System.out.println(e);}
}
private String cif;
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
public ArrayList<Logic> getLogics() {
return logics;
}
public Logic() {
}
public Logic(String cif) throws ParseException {
this.cif = cif;
connect();
}
public String getCif() {
return cif;
}
public void setCif(String cif) {
this.cif = cif;
}
}
On line 67 -> final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
it gives me this error in Netbeans: unreported exception ParseException; must be caught or declared to be thrown.
I tried surrounding it in try catch but it gives other errors in other parts of code...what can I do so I can run app ?
Thanks in advance
From what I understand, you tried something like
try {
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
The problem is, that line is not inside a method, and you can't use try...catch there.
A quick way to solve this is to put that initialization in a static block
public class Logic {
final static private ArrayList<Logic> logics;
static {
try {
logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
}
// rest of your class...
}
But honestly I have to wonder why you declared logics as static. It's not apparent from the rest of your code. Also, I see you have a non-static getLogics() method. So I'd say, if there's really no reason to declare it as static, just make it non-static and initialize it in the constructor, where you can use try...catch to your heart's content.
I have a json file, for example:
{
"A":"-0.4",
"B":"-0.2",
"C":"-0.2",
"D":"X",
"E":"0.2",
"F":"0.2",
"J":"0.3"
}
I want return each element of a list json when I call it via my function.
I did a function to do this:
public JSONObject my_function() {
JSONParser parser = new JSONParser();
List<JSONObject> records = new ArrayList<JSONObject>();
try (FileReader reader = new FileReader("File.json")) {
//Read JSON file
Object obj = parser.parse(reader);
JSONObject docs = (JSONObject) obj;
LOGGER.info("read elements" + docs); // it display all a list of a json file like this: {"A":"-0.4","B":"-0.2","C":"-0.2","D":"X","E":"0.2","F":"0.2","J":"0.3"}
for (int i = 0; i < docs.size(); i++) {
records.add((JSONObject) docs.get(i));
System.out.println((records)); // it return null
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
LOGGER.info("The first element of a list is:" +records.get(0)); // return null
return records.get(0);
How can I change my function to return the value of each element in a json file.
For example, when I call my_function:
my_function.get("A") should display -0.4
Thank you
First you need a Class for mapping
public class Json {
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String j;
//getters and setters
}
Then in your working class
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Json jsn = mapper.readValue(new File("File.json"), Json.class);
then you can use that object in a usual way...
here is the dependency I used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Reference
In Java you can use only class`s methods, as I know.
If you want to get your second element by its first, you should in your class create 2 methods like
class Main {
Map<String, String> records = new HashMap<>();
public JSONObject my_function() {
// your realization where you should insert your pairs into Map.
}
public String get(String firstElement){
return map.getValue(firstElement);
}
}
class someOtherClass {
Main main = new Main();
main .my_function();
main .get("A");
}
I want to store the json array sent by php code in java array in android. My php code is working perfectly fine but in the app I get name: as the output. I want to display the names in the texview for checking purpose. Also I want to work with the namesby accessing them one by one.
Php code:
echo json_encode(array("result"=>$result));
Java code:
public class Salary {
public static final String DATA_URL1 = "http://********.com/name.php?salary=";
public static final String KEY_name = "name";
public static final String JSON_ARRAY1 = "result";
}
This is a method of my Name.java
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Salary.JSON_ARRAY1);
for (int i = 0; i < result.length(); i++) {
JSONObject collegeData = result.getJSONObject(i);
name = collegeData.getString(Salary.KEY_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult1.setText("Name:\t" + name);
}
Use GSON Library
ArrayList<Salary> salaryArrayList = new ArrayList<>();
try {
salaryArrayList = new Gson().fromJson(response, new TypeToken<Salary>() {}.getType());
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
Then use salaryArrayList to get values.
Download GSON jar from this link
I'm new to Stackoverflow, so here goes.
I'm currently working on an assignment that requires to read from a csv file and place it into some sort of data collection.
I've gone with an arraylist. But what I seem to be stuck with is that I'm attempting to use my ReadWriteFile class to read the csv file into an arraylist (which works). But I need to somehow access that array in my GUI class to fill my JTable with said data.
After looking through similar help requests, I haven't been able to find any success.
My current code from my ReadWriteFile class;
public static void Read() throws IOException {
String lines = "";
String unparsedFile = "";
String dataArray[];
String col[] = { "COUNTRY", "MILITARY", "CIVILIAN", "POWER" };
FileReader fr = new FileReader("C:/Users/Corbin/Desktop/IN610 - Assignment 1/Programming3_WWII_Deaths.csv");
BufferedReader br = new BufferedReader(fr);
while ((lines = br.readLine()) != null) {
unparsedFile = unparsedFile + lines;
}
br.close();
dataArray = unparsedFile.split(",");
for (String item : dataArray) {
System.out.println(item);
}
ArrayList<String> myArrayList = new ArrayList<String>();
for (int i = 0; i < dataArray.length; i++) {
myArrayList.add(dataArray[i]);
}
}
So what my question is; How can I create a method that returns the values from the array, so I can access that array in my GUI class and add each element to my JTable?
Thanks!
Here is some simple example of how to return array in the method and how to use it in GUI class:
public class Main {
public String[] readFromFile (String filePath) {
ArrayList<String> yourList = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
// read file content to yourList
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return yourList.toArray(new String[yourList.size()]);
}
}
And the GUI class:
public class GUI extends JFrame {
private JTable jTable;
public GUI() {
jTable = new JTable(10, 10);
this.getContentPane().add(jTable);
this.setVisible(true);
this.pack();
}
public void passArrayToTable(Main mainClass) {
String[] array = mainClass.readFromFile("C:\\file.csv");
// for (String s : array) {
// add values to jTable with: jTable.setValueAt(s,row,column);
// }
}
public static void main(String[] args) {
new GUI().passArrayToTable(new Main());
}
}
I have a JAR file which I have imported in my project, in that a method returns an ArrayList. I have defined the object with same definition as in JAR file in my project (Here I get type mismatch error).
So my question is that how can the ArrayList in the JAR file can be assigned to an ArrayList in my project with same definition.
Code in the JAR file
public final class XMLReaderClass implements XMLReader {
private static ArrayList<CountryVO> details;
#Override
public ArrayList<CountryVO> read(InputStream fIn) {
// TODO Auto-generated method stub
if(details == null){
details = new ArrayList<CountryVO>();
try{
Document doc=parseXml(ReadFromfile(fIn));
NodeList n = doc.getElementsByTagName("Country");
for(int i=0; i < n.getLength(); i++){
CountryVO countryVO = new CountryVO();
Element e = (Element)n.item(i);
//Read individual elements
Element countryNameEl = (Element) e.getElementsByTagName("CountryName").item(0);
Element countryCodeEl = (Element) e.getElementsByTagName("CountryCode").item(0);
String countryName = countryNameEl.getLastChild().getNodeValue();
String countryCode = countryCodeEl.getLastChild().getNodeValue();
countryVO.setCountryName(countryName);
countryVO.setCountryCode(countryCode);
details.add(countryVO);
}
}catch(Exception e){
e.printStackTrace();
}
}
return details; // The data in this ArrayList should be accessed in the project where jar is imported
}
Code in the Activity
public class MyApp extends Activity {
private ListView ls;
private ArrayList<CountryVO> list;
Context context;
InputStream fIn = null;
InputSource inputSource = null;
FirstClass fclass = new FirstClass(); // Creating an instance of a class inside the JAR file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myApp);
try {
fIn = context.getResources().getAssets().open("DataFile.xml");
inputSource = new InputSource(fIn);
} catch (Exception e) {
e.printStackTrace();
}
XMLReader xmlr = fclass.read("xml");
list = xmlr.read(fIn); // Here I am getting Type Mismatch error because list is created in the activity(MyApp) and arraylist which method is returning is of other type
}
}
My Question
How to retrieve data from a JAR file and assign to a object in the app.
Here in my case the JAR is returning an ArrayList of values which I have to access in my app.
Kindly help me as I am stuck at this point. Thank you
Looks like your ArrayList must be referring to your local object while the arraylist form jar is referring to its own object avoid using your local object and import the same CountryVO object from your jar