0% found this document useful (0 votes)
51 views16 pages

Lecture Codes

The document discusses several topics related to data representation and file input/output in Java: 1) It shows how to read the contents of a file in Java and return it as a string. It also demonstrates converting a JSON object to a Java object using an ObjectMapper. 2) Examples are given for populating an HTML table with data from a JSON file using JavaScript. Requests can also be made to an API to dynamically load data. 3) The document discusses finding the average value of a column in a CSV file in Java and counting word frequencies in files within a directory to create a merged frequency map.

Uploaded by

Manal Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views16 pages

Lecture Codes

The document discusses several topics related to data representation and file input/output in Java: 1) It shows how to read the contents of a file in Java and return it as a string. It also demonstrates converting a JSON object to a Java object using an ObjectMapper. 2) Examples are given for populating an HTML table with data from a JSON file using JavaScript. Requests can also be made to an API to dynamically load data. 3) The document discusses finding the average value of a column in a CSV file in Java and counting word frequencies in files within a directory to create a merged frequency map.

Uploaded by

Manal Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Module 3: Data Representation and JAX-RS

READING A FILE CONTENT FROM A DATA FILE

import java.io.IOException;
import java.nio.file.Files;

public class CustomerUtility {

// this will read the file and return a string


public static String readFileContents(String filename) {

// this is finding the path for the file


try {
java.nio.file.Path file = java.nio.file.Path.of(
// this is going to return the URI in String format
String.valueOf(

CustomerUtility.class.getResource(filename))
.substring(6)); // will return a substring of
the URI where it will delete 'http:/" which is generated automatically
return Files.readString(file);

} catch (IOException e) {
// something went wrong
return "Did you forget to create the file?\n" +
"Is the file in the right location?\n" +
e.toString();
}
}
}

Converting from a JSON object to Java object


public class CustomerResource {
Customers customersList;

// will convert to and from a json object to a java object


ObjectMapper objectMapper = new ObjectMapper(); // this is a built-in
function from the Jackson library

// this is initializing the data and calling the mapping function


CustomerResource() {
loadResource();
}

private void loadResource(){


try {
// reading from the json file converting to a java object
this.customersList =
objectMapper.readValue(readFileContents("/customers.json"),
Customers.class); // mapping the customers json object to java object
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}

public class Customers {

// this will store a list of customer objects which maps to the key
customers in the json object
@JsonProperty("customers")
public List<Customer> customersList;

// will allow you to return one customer ID if it finds it in the list


public Customer findCustomerId(String id){
Customer cfound = null;
for(Customer c: customersList){ // loop through list of
customers
if (Objects.equals(c.getId(), id)){ // if the id is found
cfound= c;
}
}
return cfound;
}
}
Module 4: REST Representation

POPULATING A TABLE WITH DATA WITH JAVASCRIPT


function loadDataAsTable(){
// setting this variable divRef to the element divTable
let divRef = document.getElementById("divTable");

// Then set this variable to the table id and APPEND this table to the
div
let tableRef = document.createElement("table");
divRef.appendChild(tableRef);

// Creating a thead variable and appending the header to the table


let tableHeaderRef = document.createElement("thead");
tableRef.appendChild(tableHeaderRef);

// Creating a tbody variable and then appending the header to the table
let tableBodyRef = document.createElement("tbody");
tableRef.appendChild(tableBodyRef);

// looping through the object key - value pairs


let headers = Object.keys(customerData.customers[0]);
// looping through each header
for (let header of headers){
// Then setting the headers to the header tag in html, then append the
headers to the table
let headerRef= document.createElement("th");
headerRef.innerHTML=header;
tableHeaderRef.appendChild(headerRef);
}

// looping through each object in the json data


for (let c of customerData.customers){
// Create a row for each object
let rowRef = document.createElement("tr");
// Then loop through each element [key-value pairs] for each json
object
for (let key in c){
// Since each key-value pair, create a table data for each
let dataRef=document.createElement("td");
// Append each key-value pair in the table data
dataRef.innerHTML=c[key];
// Then append the table data into the table rows
rowRef.appendChild(dataRef);
}

// Then append the rows to the table


tableRef.appendChild(rowRef);
}
}

// ----------------- Returning a response from the API


----------------------- //
@GET
@Produces("application/json")
public Response getAllCustomers() { // will return a response object
using the CORS policy
loadResource();
String val = "Problem";
try {
val = objectMapper.writeValueAsString(customersList); // will
be converting the json to java here
} catch (JsonProcessingException e) { // handling exceptions
throw new RuntimeException(e);
}

// CORS Policy is a security measure that does not allow you to


run a file from one domain in another domain. It is blocked by default
// So you can manually set the port that the domain you are trying
to return is in

// creating a response
Response myResp = Response.status(200)
.header("Access-Control-Allow-Origin",
"http://localhost:8448") // this will allow the localhost 8448 to be
hosted
.header("Content-Type", "application/json") // the data
returning will be json format
.entity(val) // the data is customers
.build();

return myResp;
}

// will request a customer json object from the findCustomerId


function
@GET
@Path("/{id}")
@Produces("application/json")
public String getCustomerId(@PathParam("id") String cId){ // will use
the path parameter id from the path URI
loadResource();
Customer c = customersList.findCustomerId(cId);
if (c!=null){ // if you cannot find a customer object then return
the object as a json property
try {
return objectMapper.writeValueAsString(c); // this will
convert the customer java object to a json object

} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}

return "{\"Error\": \"Customer not found.\"}";

}
}

/**
* Function makes a HTTP request to an API
* **/
function requestData(apiCallURL){
// the fetch request is an asynchronous request to an API
fetch(apiCallURL, {
// defining request headers in the fetch request
method: 'GET',
headers: {
'Accept': 'application/json',
},
})
.then(response => response.json())
.then(response => loadDataAsTable("customers", response)); // this
will dynamically make the data inputted into the table in the html file
}

Module 5: File Input/Output

public class ExampleParser {


private File directory = null;
ExampleParser(File dir){
this.directory = dir;
}

// finding the average for each column (e.g assignment1 grades, etc)
public String findColumnAVG(String col){
// File inFile = new File();
String columnName = col;
String msg = "Not found or error occurred";

try {
FileReader fileInput = new FileReader(directory);
BufferedReader input = new BufferedReader(fileInput);

// read the first line


String line = null;
try {
line = input.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}

// find the index of the named column


int columnIndex = -1;
String[] columnNames = line.split(","); // will split the line
at each column
for (int i = 0; i < columnNames.length; i++) {
if (columnNames[i].equals(columnName)) {
columnIndex = i;
break;
}
}

// there must be an error if the column is less than 0


if (columnIndex < 0) {
System.err.println("Error: Column name not found");
System.exit(0);
}

// calculate the average for that column


float total = 0f;
int count = 0;

// reading line by line


while ((line = input.readLine()) != null) {
String[] data = line.split(",");
float nextVal = Float.parseFloat(data[columnIndex]); //
will convert to float since our data is in floats
total += nextVal;
count++;
}

msg = "The average for "+ columnName+" is "+ (total/count);

input.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
public class BookParser {

public Map<String, Integer> wordFrequencyDir(File dir) throws


IOException {
Map<String, Integer> frequencies = new TreeMap<>(); // will hold
all the merged frequency maps

File[] filesInDir = dir.listFiles();


int numFiles = filesInDir.length;

// iterate over each file in the dir and count their words
for (int i = 0; i<numFiles; i++){
Map<String, Integer> wordMap = countWordFile(filesInDir[i]);
// get a frequency map between the word and its frequency

// merge the file wordMap into the global frequencies


Set<String> keys = wordMap.keySet(); // will get the set of
the keys in the frequency map
Iterator<String> keyIterator = keys.iterator();
while (keyIterator.hasNext()){
String word = keyIterator.next();
int count = wordMap.get(word);

if(frequencies.containsKey(word)){
// increment
int oldCount = frequencies.get(word);
frequencies.put(word, count + oldCount);
}
else{
frequencies.put(word, count);
}
}

return frequencies;
}

}
Function to count the words in the file
private Map<String, Integer> countWordFile(File file) throws
IOException {
Map<String, Integer> wordMap = new TreeMap<>();
if(file.exists()){
// load all the data and process it into words
Scanner scanner = new Scanner(file); // note: a scanner will
by default use a white space as a delimiter
while(scanner.hasNext()){
// ignore the casing for words
String word = (scanner.next()).toLowerCase(); // will
convert all uppercase letters to lowercase so the same word is not
duplicated
if (isWord(word)){ // only if the string is a word, then
add it in the map
// add the word if not exists yet
if(!wordMap.containsKey(word)){
wordMap.put(word, 1);
}
// increment the count if exists
else{
int oldCount = wordMap.get(word);
wordMap.put(word, oldCount+1);
}
}
}
}
return wordMap;
}

// Checking is word is actually a word (not a number, etc)


private Boolean isWord(String word){
if (word == null){
return false;
}
String pattern = "^[a-zA-Z]*$"; // this is checking if it has
alphabets in it consecutively.
if(word.matches(pattern)){
return true;
}

return false;

Function to write to a file

public class ExampleWriter {

public void createFile(File dir, String name, String content) throws


IOException {
File myFile = null;

myFile = new File(dir, name);


if(myFile.createNewFile()){
System.out.println("File created at: "+ myFile.getPath());
}else{
System.out.println("File already existed at: "+
myFile.getPath());
}

if(myFile!=null){
PrintWriter output = new PrintWriter(myFile);
output.print(content);
output.close();
}

}
}

// Will read the data in the specified url and find the column name
and then store it in the string
public String readData(@PathParam("col") String colName) {
URL url =
this.getClass().getClassLoader().getResource("/records/data.csv"); // This
will get the url for the specified file we want to read
System.out.print(url);

File data = null;


try {
data = new File(url.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}

String res = "Something went wrong";


if (data!=null){
ExampleParser myparser = new ExampleParser(data);
res = myparser.findColumnAVG(colName);
}

return res;
}

// Will return the frequency of each word


@GET
@Produces("application/json")
@Path("/book")
/**
* Endpoint URL:
http://localhost:8080/ParsingFiles-1.0-SNAPSHOT/api/read/book
* **/

public Response readBook() throws IOException {


URL url =
this.getClass().getClassLoader().getResource("/documents"); // this will
get the url of the of the class
File data = null;
try {
data = new File(url.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
BookParser myParser = new BookParser();
// call function from parser to calculate the freq of words in
text
Map<String, Integer> freq = myParser.wordFrequencyDir(data);
System.out.println("-----------------Hello world!");

Response myResp =
Response.status(200).header("Access-Control-Allow-Origin",
"http://localhost:8448")
.header("Content-Type", "application/json")
.entity(mapper.writeValueAsString(freq)) // since we have
a map object and we need a json object, we will use the jackson library
.build();

return myResp;
}

Writing data to the server


@POST
@Consumes("text/plain")
@Path("/save")
public Response save(String content) throws IOException {
Map<String, Object> result = mapper.readValue(content,
HashMap.class);

String title = (String) result.get("title");


String body = (String) result.get("content");

URL url =
this.getClass().getClassLoader().getResource("/records");
File data = null;
try {
data = new File(url.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}

ExampleWriter myWriter = new ExampleWriter();


myWriter.createFile(data, title, body);

Response myResp = Response.status(200)


.header("Access-Control-Allow-Origin",
"http://localhost:8448")
.header("Content-Type", "application/json")
.build();

return myResp;

Module 6: Network Programming; TCP, UDP, and Sockets

public class BookData {

public static void main(String[] args) throws IOException {

System.out.println("Hello world!");

String url =
"http://localhost:8080/ParsingFiles-1.0-SNAPSHOT/api/read/book";
URL netURL = new URL(url);

URLConnection conn = netURL.openConnection();


conn.setDoOutput(false);
conn.setDoInput(true);

InputStream inStream = conn.getInputStream();


BufferedReader in = new BufferedReader(new
InputStreamReader(inStream));

System.out.println(url);

StringBuffer buffer = new StringBuffer();


String line;
while ((line = in.readLine()) != null) {
buffer.append(line);
}
String jsonData = buffer.toString();

System.out.println(jsonData);

Transforming the string into objects using org.json library


JSONObject data = new JSONObject(jsonData);
Map<String, Object> mapData = data.toMap();

Set<String> keys = mapData.keySet();


Iterator<String> keyIterator = keys.iterator();

// iterating over items in the map


while(keyIterator.hasNext()){
String word = keyIterator.next();
int count = (int) mapData.get(word);
System.out.printf("Found: %s (%s)\n", word, count);
}

inStream.close();
}
}

public class BikeShare {


public static void main(String[] args) throws IOException,
ParserConfigurationException, SAXException {
// create URL
String url =
"https://api.mockaroo.com/api/e9cc2e00?count=20&key=e99c5530"; //
accessing this mock api, generates random information
URL netURL = new URL(url);

URLConnection conn = netURL.openConnection();


// we are doing a GET request
conn.setDoOutput(false);
conn.setDoInput(true);

// load the data using a URLConnection


InputStream inStream = conn.getInputStream();
// DocumentBuilder to parse the XML data
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
Document document = docBuilder.parse(inStream);
document.getDocumentElement().normalize(); // remove any extra
whitespace, and format correctly

NodeList itemNodes = document.getElementsByTagName("station");

// iterating over all the stations


for (int i = 0; i < itemNodes.getLength(); i++) {
Node itemNode = itemNodes.item(i);
// retrieve properties for each station
if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
Element itemElement = (Element)itemNode;

// read each individual property


String name = getTagValue("name", itemElement);
String lat = getTagValue("lat", itemElement);
String lon = getTagValue("long", itemElement);
String num = getTagValue("nbBikes", itemElement);
String id = getTagValue("id", itemElement);

// output the formatted date into the console


System.out.printf("[%s] %s (%s, %s): %s bikes
available.\n",
id,
name,
lat,
lon,
num
);

}
}
}

private static String getTagValue(String name, Element itemElement) {


NodeList tags = itemElement.getElementsByTagName(name);
if(tags.getLength()>0) {
return tags.item(0).getTextContent(); // get the textcontent
of the first item
}

return null;
}
}

You might also like