Results 1 to 5 of 5
  1. #1
    prathesh.bv is offline Member
    Join Date
    Sep 2014
    Posts
    14
    Rep Power
    0

    Question Exception in thread "main" java.lang.ClassCastException in JSON

    Hi Im trying to get the Json file from an application and parse the Json file then get the agents which is offline , so the offline agents are attached in mail and published to team.

    Java Code:
    
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.InetAddress;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    import java.util.Iterator;
    import java.util.Properties;
    
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
    
    public class AgentStatus {
    
    	public static void main(String[] args) throws ParseException {
    
    		try {
    
    			String filename = "E://agent.xls";
    			HSSFWorkbook hwb = new HSSFWorkbook();
    			HSSFSheet sheet = hwb.createSheet("Build_agents");
    
    			HSSFRow rowhead = sheet.createRow((short) 0);
    
    			rowhead.createCell((short) 0).setCellValue("Agent_name");
    
    			rowhead.createCell((short) 1).setCellValue("Agent_status");
    
    			// Sets the authenticator that will be used by the networking code
    			// when a proxy or an HTTP server asks for authentication.
    			Authenticator.setDefault(new CustomAuthenticator());
    
    			URL url = new URL("http://testdeploy-t1:8081/rest2/agents");
    
    			// read text returned by server
    			BufferedReader in = new BufferedReader(new InputStreamReader(url
    					.openStream()));
    
    			String line;
    
    			while ((line = in.readLine()) != null) {
    
    				FileOutputStream fop = null;
    				File file;
    
    				file = new File("E:/Jarfiles/Results.json");
    				fop = new FileOutputStream(file);
    				byte[] contentInBytes = line.getBytes();
    
    				fop.write(contentInBytes);
    				fop.flush();
    				fop.close();
    
    			}
    			in.close();
    			String filePath = "E:/Jarfiles/Results.json";
    
    			FileReader reader = new FileReader(filePath);
    
    			System.out.println("The unavailability of Ubuild agents");
    
    			JSONParser jsonParser = new JSONParser();
    			/*
    			 * JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
    			 * JSONObject structure = (JSONObject) jsonObject.get("response");
    			 */
    			// Object[] result=(Object[]) structure.get("results");
    			Object obj = jsonParser.parse(new FileReader(
    					"E://Jarfiles//Results.json"));
    			JSONObject jsonObject = (JSONObject) obj;
    			// Object gu_obj = jsonObject.get("guid");
    			JSONArray lang = (JSONArray) jsonObject.get("results");
    
    			System.out.println(lang.size());
    			for (int i = 0; i < lang.size(); i++) {
    
    				// System.out.println("The " + i +
    				// " element of the array: "+lang.get(i));
    
    			}
    			Iterator i = lang.iterator();
    
    			int j = 1;
    			while (i.hasNext()) {
    
    				JSONObject innerObj = (JSONObject) i.next();
    				// System.out.println("innerobj" +innerObj);
    
    				if (innerObj.get("status").equals("Offline")) {
    
    					// System.out.println(innerObj.get("name"));
    					// System.out.println(innerObj.get("status"));
    					HSSFRow row = sheet.createRow((short) j);
    
    					row.createCell((short) 0).setCellValue(
    							innerObj.get("name").toString());
    
    					sheet.autoSizeColumn(0);
    					row.createCell((short) 1).setCellValue(
    							innerObj.get("status").toString());
    					sheet.autoSizeColumn(1);
    					j++;
    				}
    
    			}
    			FileOutputStream fileOut = new FileOutputStream(filename);
    			hwb.write(fileOut);
    
    			fileOut.close();
    			// Udeployagent10 crf= new Udeployagent10();
    
    			try {
    				if (j != 1) {
    					Access_password_correct1 mail = new Access_password_correct1();
    					mail.mail1();
    				} else {
    					System.out.println("all agents are online");
    				}
    			} catch (AddressException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (MessagingException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    
    		} catch (IOException ex) {
    			ex.printStackTrace();
    		}
    
    	}
    
    	public void mail1() throws AddressException, MessagingException {
    
    		String host = "mail.gmail.com";
    		String from = "SCM_Team@gmail.com";
    		String to = "pradeesh@gmail.com";
    		String fileAttachment = "E://agent.xls";
    		Properties props;
    		MimeMessage message;
    		Session session;
    		StringBuffer msg = new StringBuffer();
    		String msg1 = "Please find the agent details below";
    		String msgBody;
    		/*
    		 * read file
    		 */
    		try {
    			InputStream input = new BufferedInputStream(new FileInputStream(
    					"E://agent.xls"));
    			POIFSFileSystem fs = new POIFSFileSystem(input);
    			HSSFWorkbook wb = new HSSFWorkbook(fs);
    			HSSFSheet sheet = wb.getSheetAt(0);
    			// int firstRow=sheet.getFirstRowNum();
    			// int lastRow=sheet.getLastRowNum();
    			msg.append("Hello Team,\n \n");
    			msg
    					.append("The unavailability of the agent(s) will impact builds/deployments that are scheduled to run on the agent.");
    			Iterator rows = sheet.rowIterator();
    
    			while (rows.hasNext()) {
    				HSSFRow row = (HSSFRow) rows.next();
    				if (row.getRowNum() > 0) {
    					msg.append("\n");
    					Iterator cells = row.cellIterator();
    
    					while (cells.hasNext()) {
    
    						// msg.append(' ');
    						msg.append("\t");
    						msg.append("\n");
    
    						HSSFCell cell = (HSSFCell) cells.next();
    						if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType())
    							msg.append(cell.getNumericCellValue());
    						else if (HSSFCell.CELL_TYPE_STRING == cell
    								.getCellType())
    							msg.append(cell.getStringCellValue());
    						else if (HSSFCell.CELL_TYPE_BOOLEAN == cell
    								.getCellType())
    							cell.getBooleanCellValue();
    					}
    
    				}
    
    			}
    
    			msg.append("\n \n \n Thanks,\n SCM Team");
    
    		} catch (IOException ex) {
    			ex.printStackTrace();
    		}
    		// msg.append("</body></html>");
    
    		msgBody = msg.toString();
    
    		// Get system properties
    		props = System.getProperties();
    
    		// Setup mail server
    		props.put("mail.smtp.host", host);
    
    		// Get session
    		session = Session.getInstance(props, null);
    		message = new MimeMessage(session);
    
    		// Define message
    
    		message.setFrom(new InternetAddress(from));
    		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    		// message.addRecipient(Message.RecipientType.TO, new
    		// InternetAddress.parse("pradeesh@gmail.com"));
    		message.addRecipients(Message.RecipientType.CC, InternetAddress
    				.parse("pradeesh@gmail.com"));
    		// message.addRecipients(Message.RecipientType.CC,
    		// InternetAddress.parse("pradeesh@gmail.com"));
    		message
    				.setSubject("Alert: One or more uBuild / uDeploy agent(s) detected to be offline");
    		// message.setText(msg1);
    		// create the message part
    		// message.setContent(o, type);
    		MimeBodyPart messageBodyPart = new MimeBodyPart();
    
    		MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    
    		// fill message
    
    		messageBodyPart.setText(msgBody);
    
    		// messageBodyPart.getFileName();
    		Multipart multipart = new MimeMultipart();
    
    		multipart.addBodyPart(messageBodyPart);
    		// multipart.addBodyPart(msg1);
    		// Part two is attachment
    		messageBodyPart = new MimeBodyPart();
    		DataSource source = new FileDataSource(fileAttachment);
    		messageBodyPart.setDataHandler(new DataHandler(source));
    		StringBuffer st = new StringBuffer(fileAttachment);
    		System.out.println(st.replace(0, 2, ""));
    		String s1 = st.toString();
    
    		messageBodyPart.setFileName(s1);
    
    		multipart.addBodyPart(messageBodyPart);
    
    		// Put parts in message
    		message.setContent(multipart);
    
    		// Send the message
    		Transport.send(message);
    		System.out.println("mail sent successfully");
    
    	}
    
    	public static class CustomAuthenticator extends Authenticator {
    
    		// Called when password authorization is needed
    		protected PasswordAuthentication getPasswordAuthentication() {
    
    			// Get information about the request
    			String prompt = getRequestingPrompt();
    			String hostname = getRequestingHost();
    			InetAddress ipaddr = getRequestingSite();
    			int port = getRequestingPort();
    			String username = "admin";
    			String password = "admin";
    			
    			return new PasswordAuthentication(username, password.toCharArray());
    
    		}
    
    	}
    
    }


    Im getting below exception while executing the code .

    Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
    at AgentStatus.main(AgentStatus.java:101)


    Please help me to resolve the issue ASAP

    below is the line im getting the exception

    JSONObject jsonObject = (JSONObject) obj;


    adding json file


    [{"id":21,"name":"SV-HSCBUILD-P2","description":null,"host":null,"status":"Offli ne","version":"N\/A","throughput":1,"activeJobs":0,"maxJobs":5,"igno red":false,"configured":true,"lastOnline":14341355 48313,"lastOnlineString":"6\/12\/15 2:59 PM"},{"id":11,"name":"svl-jbuild-d1-t1","description":"svl-jbuild-d1-t1","host":null,"status":"Online","version":"5.0 .0-432508","throughput":1,"activeJobs":0,"maxJobs":5, "ignored":false,"configured":true,"lastOnline":145 5742763727,"lastOnlineString":"2\/17\/16 3:59 PM"},{"id":201,"name":"T1BuildAgent","description" :null,"host":null,"status":"Online","version":"6.1 .0-637672","throughput":1,"activeJobs":0,"maxJobs":5, "ignored":false,"configured":true,"lastOnline":145 5742778797,"lastOnlineString":"2\/17\/16 3:59 PM"},{"id":65,"name":"Tibco-SVTIBBUILD","description":null,"host":null,"status ":"Online","version":"5.0.0-432508","throughput":1,"activeJobs":0,"maxJobs":5, "ignored":false,"configured":true,"lastOnline":145 5742778670,"lastOnlineString":"2\/17\/16 3:59 PM"},{"id":192,"name":"Tibco_t1","description":nul l,"host":null,"status":"Online","version":"6.1.0-637672","throughput":1,"maxJobs":5,"ignored":false ,"configured":false,"lastOnline":1455742778047,"la stOnlineString":"2\/17\/16 3:59 PM"}]

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Exception in thread "main" java.lang.ClassCastException in JSON

    It looks to me like you are getting that error on a different statement. Have you checked the API to ensure you are doing correct casts. You might also
    try using some print statements to see the object types.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Exception in thread "main" java.lang.ClassCastException in JSON

    Your JSON file is an array.
    The outer element is [], which is an array, so that is the object that's read.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    prathesh.bv is offline Member
    Join Date
    Sep 2014
    Posts
    14
    Rep Power
    0

    Default Re: Exception in thread "main" java.lang.ClassCastException in JSON

    So what type of parsing I need to do , or no need of json parsing?

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Exception in thread "main" java.lang.ClassCastException in JSON

    Java Code:
                Object obj = jsonParser.parse(new FileReader("E://Jarfiles//Results.json"));
                JSONObject jsonObject = (JSONObject) obj;
    Here is your issue.
    You read the file and then expect the first thing parsed to be a JSONObject.
    It's not.
    It's a JSONArray.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 2
    Last Post: 06-20-2012, 12:18 AM
  2. Replies: 5
    Last Post: 12-21-2011, 06:44 PM
  3. Replies: 14
    Last Post: 04-08-2011, 06:01 PM
  4. Exception in thread "main" java.lang.ClassCastException:
    By extremeshannon in forum Java Applets
    Replies: 9
    Last Post: 07-27-2010, 06:00 PM
  5. Replies: 5
    Last Post: 06-22-2010, 03:51 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •