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();
Related
I use Java mail APIs from a spring web application to send a weekly email to an outlook mail.
The feature was behaving normally for the first couple of weeks, then without any changes outlook received two emails, the next week three emails were received, then four, then five emails.
The logs set in the Java code indicates that only one email is being sent from the application.
I can't replicate the issue by changing the schedule to send each 15 minutes, or hour, or any shorter interval.
Email controller class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class WeeklyReportScheduler {
#Autowired
private WeeklyReportService weeklyReportService;
#Scheduled(cron = "${cron.expression}")
public void sendWeeklyReport(){
weeklyReportService.sendWeeklyReport();
}
}
Email service class:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.stereotype.Service;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Service
public class WeeklyReportService {
#Value("${weekly.report.mail.subject}")
private String subject;
#Value("${weekly.report.mail.body}")
private String mailBody;
#Value("${mail.body.empty.report}")
private String emptyReportMailBody;
#Value("${receiver}")
private String receiver;
#Autowired
private MailService mailService;
#Autowired
private WeeklyReportLogDao weeklyReportLogDao;
#Autowired
private ProjectService projectService;
#Value("${export.path}")
private String exportDir;
protected final Log logger = LogFactory.getLog(getClass());
public void sendWeeklyReport(){
boolean emptyReport = true;
//retrieving attachment data 'projects'
if(projects.size() != 0){
emptyReport = false;
}
String body = "";
if(emptyReport){
body = emptyReportMailBody;
} else {
body = mailBody;
}
SimpleDateFormat format = new SimpleDateFormat("MM/dd/YYYY");
String dateString = format.format(new Date());
String mailSubject = subject + " " + dateString;
List recipients = new ArrayList<String>();
recipients.add(receiver);
String fileName = mailSubject.replace(" ", "_").replace("/", "_");
WeeklyReportExcelExport excelExport = new WeeklyReportExcelExport(exportDir, fileName);
excelExport.createReport(projects);
File excelFile = excelExport.saveToFile();
File[] attachments = new File[1];
attachments[0] = excelFile;
boolean sent = false;
String exceptionMessage = "";
for(int i=0; i<3; i++){
try {
logger.info("Sending Attempt: " + i+1);
Thread.sleep(10000);
mailService.mail(recipients, mailSubject, body, attachments);
sent = true;
break;
} catch (Exception ex) {
logger.info("sending failed because: " + ex.getMessage() + " \nRe-attempting in 10 seconds");
exceptionMessage = ex.getMessage();
sent = false;
}
}
if(!sent){
weeklyReportLogDao.logFailedReporting(dateString, exceptionMessage);
}
//re-try 3 times in case of mail sending failure
}
MailService class:
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailServiceImpl implements MailService {
/** The From address for the e-mail. read from ant build properties file */
private String fromAddress;
/** The mail sender. */
private JavaMailSender mailSender;
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public void mail(List<String> emailAddresses, String subject, String text, File[] attachments) throws MailException {
//System.out.println("mail: "+subject);
MimeMessage message = null;
// Fill in the From, To, and Subject fields.
try {
message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
messageHelper.setFrom(fromAddress);
for (String emailAddress : emailAddresses) {
messageHelper.addTo(emailAddress);
}
messageHelper.setSubject(subject);
// Fill in the body with the message text, sending it in HTML format.
messageHelper.setText(text, true);
// Add any attachments to the message.
if ((attachments != null) && (attachments.length != 0)) {
for (File attachment : attachments) {
messageHelper.addAttachment(attachment.getName(), attachment);
}
}
}
catch(MessagingException mse) {
String warnMessage = "Error creating message.";
logger.warn(warnMessage);
throw (new RuntimeException(warnMessage, mse));
}
try {
mailSender.send(message);
} catch (Exception ex){
logger.info("Exception sending message: " + ex.getMessage());
}
}
}
you might have duplicate entries on your argument emailAddresses, try moving it to treeset if you cant ensure duplicate entries from the repository layer
Hi i have created a handler in java for getting the events from dynamo DB
Here is my code
package com.Lambda.dynamodb;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
public class DDBEventProcessor implements
RequestHandler<DynamodbEvent, String> {
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()){
System.out.println(record.getEventID());
System.out.println(record.getEventName());
System.out.println(record.getDynamodb().toString());
}
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
}
}
Lambda function able to write the events in cloudwatch but the challenge is i have to index all the streamed records to the AWS elasticsearch service endpoint and index it.
while search through blogs i got few code samples in python and node.js but my requirement is i have to build this lambda function in java
Could anyone please suggest how to achieve this in java lambda function?
Hi i have included the code below may helpful to some one. Dynamo DB streams to index the document in elasticsearch both inside AWS and outside AWS
package com.Firstlambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemUtils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HelloWorld implements RequestHandler<DynamodbEvent, String> {
private static String serviceName = "es";
private static String region = "us-east-1";
private static String aesEndpoint = ""
private static String index = "";
private static String type = "_doc";
static final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()) {
System.out.println("EventName : " + record.getEventName());
System.out.println("EventName : " + record.getDynamodb());
//AWS outside
RestHighLevelClient esClient = esClient();
//AWS outside
//AWS Inside
//RestHighLevelClient esClient = esClient(serviceName, region);
//AWS Inside
if (record.getEventName().toLowerCase().equals("insert")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
IndexRequest indexRequest = new IndexRequest(index, type, JsonUniqueId);
indexRequest.source(JsonString, XContentType.JSON);
try {
IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else if (record.getEventName().toLowerCase().equals("modify")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
UpdateRequest request = new UpdateRequest(index, type, JsonUniqueId);
String jsonString = JsonString;
request.doc(jsonString, XContentType.JSON);
try {
UpdateResponse updateResponse = esClient.update(
request, RequestOptions.DEFAULT);
System.out.println(updateResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("remove");
System.out.println("KEYID : " + record.getDynamodb().getKeys().get("ID").getN());
String deletedId = record.getDynamodb().getKeys().get("ID").getN();
DeleteRequest request = new DeleteRequest(index, type, deletedId);
try {
DeleteResponse deleteResponse = esClient.delete(
request, RequestOptions.DEFAULT);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return "Successfullyprocessed";
}
public String getJsonstring(Map<String, AttributeValue> newIma) {
String json = null;
Map<String, AttributeValue> newImage = newIma;
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>();
listOfMaps.add(newImage);
List<Item> itemList = ItemUtils.toItemList(listOfMaps);
for (Item item : itemList) {
json = item.toJSON();
}
return json;
}
public String GetIdfromJsonString(String Json) {
JSONObject jsonObj = new JSONObject(Json);
return String.valueOf(jsonObj.getInt("ID"));
}
// Adds the interceptor to the ES REST client
// public static RestHighLevelClient esClient(String serviceName, String region) {
// AWS4Signer signer = new AWS4Signer();
// signer.setServiceName(serviceName);
// signer.setRegionName(region);
// HttpRequestInterceptor interceptor = new AWSRequestSigningApacheInterceptor(serviceName, signer, credentialsProvider);
// return new RestHighLevelClient(RestClient.builder(HttpHost.create(aesEndpoint)).setHttpClientConfigCallback(hacb -> hacb.addInterceptorLast(interceptor)));
// }
public static RestHighLevelClient esClient() {
String host = "d9bc7cbca5ec49ea96a6ea683f70caca.eastus2.azure.elastic-cloud.com";
int port = 9200;
String userName = "elastic";
String password = "L4Nfnle3wxLmV95lffwsf$Ub46hp";
String protocol = "https";
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
This is just a sample code has to be modified based on our requirements
Java class
package voteHandler.Org.RSPSVote;
/*
* Author: Sieu Phan
* Website: RSPS Vote
* Data: 5/7/2014
* Version: 1.1
*/
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class voteHandler {
private static String SERVER = "";
private static String API_KEY = "";
public voteHandler(String SERVER_TO_SET, String API_KEY_TO_SET)
{
SERVER = SERVER_TO_SET;
API_KEY = API_KEY_TO_SET;
}
/*
Sends a GET request to RSPS Vote API.
RETURNS: a boolean
*/
public static boolean authenticate(String AUTH)
{
String url = generateURL(AUTH);
try {
String getJSON = IOUtils.toString(new URL(url));
JSONObject message = (JSONObject) JSONValue.parseWithException(getJSON);
String messageData = (String) message.get("MESSAGE");
System.out.println(messageData);
int responseData = Integer.parseInt((String) message.get("RESPONSE"));
System.out.println(responseData);
if(responseData == 5)
return true;
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return false;
}
public static boolean getReward(String AUTH)
{
String url = generateURL(AUTH);
return false;
}
/*
Generates the url to the API
RETURNS: a String
*/
private static String generateURL(String AUTH)
{
String URL = "http://rspsvote.com/widget/api.php?"
+ "action=check"
+ "&server=" + SERVER
+ "&key=" + API_KEY
+ "&auth=" + AUTH;
return URL;
}
}
Testing class
import voteHandler.Org.RSPSVote.voteHandler;
public class testing {
public static void main(String args[])
{
voteHandler vote = new voteHandler("l6DZw", "ELWXQ-MI4BC-3K1RT-VUKPT-DGL2U");
vote.authenticate("Ptpz1n");
}
}
what's wrong with this JSON format being returned from the site?
http://rspsvote.com/widget/api.php?key=ELWXQ-MI4BC-3K1RT-VUKPT-DGL2U&action=check&auth=Ptpz1n&server=l6DZw
Also this is the error I get from eclipse:
Unexpected character (<) at position 63.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at org.json.simple.JSONValue.parseWithException(JSONValue.java:78)
at voteHandler.Org.RSPSVote.voteHandler.authenticate(voteHandler.java:34)
at testing.main(testing.java:8)
what's wrong with this JSON format being returned from the site?
It doesn't return JSON. The response's content type is text/html and the body contains
{"RESPONSE":"7","MESSAGE":"AUTHENTICATION WAS UNSUCCESSFUL."}
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
You'll need to get rid of the XML or stop parsing after the JSON.
Hello I am trying to develop my web application using jsp. I have 6 jsp pages in it. Pages are registration.jsp, login.jsp, r1.jsp, welcome.jsp, createroom.jsp and showroom.jsp respectivly. My goal is that when i login in login page, page should redirect in openmeeting server. For that i have created webservice like omRestService. For calling this Service i have created two java class omGateWay and OmPluginSettings respectivly. Everything works fine but error occurs in ompluginSetting class.error mention below.
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
(The import com.atlassian cannot be resolved)
Here I am Providing you my OmPluginSeeting.java file which has error. There are many errors occur at PluginSettingsFactory.
package restService;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OmPluginSettings
{
private static final Logger log = (Logger) LoggerFactory.getLogger(OmPluginSettings.class);
final PluginSettingsFactory pluginSettingsFactory;
public OmPluginSettings(PluginSettingsFactory pluginSettingsFactory)
{
this.pluginSettingsFactory = pluginSettingsFactory;
}
public void storeSomeInfo(String key, String value)
{
this.pluginSettingsFactory.createGlobalSettings().put("openmeetings:" + key, value);
}
public Object getSomeInfo(String key)
{
return this.pluginSettingsFactory.createGlobalSettings().get("openmeetings:" + key);
}
public void storeSomeInfo(String projectKey, String key, String value)
{
this.pluginSettingsFactory.createSettingsForKey(projectKey).put("openmeetings:" + key,
value);
}
public Object getSomeInfo(String projectKey, String key) {
return this.pluginSettingsFactory.createSettingsForKey(projectKey).get("openmeetings:"
+ key);
}
}
I also provide my restservice which is Given Below and totally error free.
package restService;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class omRestService
{
private static final Logger log = (Logger)
LoggerFactory.getLogger(omRestService.class);
private URI getURI(String url) {
return UriBuilder.fromUri(
url).build(new Object[0]);
}
private String getEncodetURI(String url) throws MalformedURLException
{
return new URL(url).toString().replaceAll(" ", "%20");
}
public LinkedHashMap<String, Element> call(String request, Object param)
throws Exception
{
HttpClient client = new HttpClient();
GetMethod method = null;
try
{
method = new GetMethod(getEncodetURI(request).toString());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
int statusCode = 0;
try {
statusCode = client.executeMethod(method);
}
catch (HttpException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
catch (IOException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
switch (statusCode)
{
case 200:
break;
case 400:
throw new Exception("Bad request. The parameters passed to the service did
not match
as expected. The Message should tell you what was missing or incorrect.");
case 403:
throw new Exception("Forbidden. You do not have permission to access this
resource, or
are over your rate limit.");
case 503:
throw new Exception("Service unavailable. An internal problem prevented us
from
returning data to you.");
default:
throw new Exception("Your call to OpenMeetings! Web Services returned an
unexpected
HTTP status of: " + statusCode);
}
InputStream rstream = null;
try
{
rstream = method.getResponseBodyAsStream();
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("No Response Body");
}
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
SAXReader reader = new SAXReader();
Document document = null;
String line;
try
{
// String line;
while ((line = br.readLine()) != null)
{
// String line;
document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
throw new Exception("UnsupportedEncodingException by SAXReader");
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("IOException by SAXReader in REST Service");
}
catch (DocumentException e) {
e.printStackTrace();
throw new Exception("DocumentException by SAXReader in REST Service");
} finally {
br.close();
}
Element root = document.getRootElement();
LinkedHashMap elementMap = new LinkedHashMap();
for (Iterator i = root.elementIterator(); i.hasNext(); )
{
Element item = (Element)i.next();
if (item.getNamespacePrefix() == "soapenv") {
throw new Exception(item.getData().toString());
}
String nodeVal = item.getName();
elementMap.put(nodeVal, item);
}
return elementMap;
}
}
After This RestService i have make OmGateWay class which has many method for integrate with openmeetings. which is given below:
package org.openmeetings.jira.plugin.gateway;
import java.util.LinkedHashMap;
import org.dom j.Element;
import org.openmeetings.jira.plugin.ao.adminconfiguration.OmPluginSettings;
import org.slf j.Logger;
import org.slf j.LoggerFactory;
public class OmGateway
{
private static final Logger log =
LoggerFactory.getLogger(OmGateway.class);
private OmRestService omRestService;
private OmPluginSettings omPluginSettings;
private String sessionId;
public OmGateway(OmRestService omRestService, OmPluginSettings omPluginSettings)
{
this.omRestService = omRestService;
this.omPluginSettings = omPluginSettings;
}
public Boolean loginUser() throws Exception
{
LinkedHashMap result = null;
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String userpass = (String)this.omPluginSettings.getSomeInfo("userpass");
String omusername =
(String)this.omPluginSettings.getSomeInfo("username");
String sessionURL = "http://" + url + ":" + port + "/openmeetings
/services/
UserService/getSession";
LinkedHashMap elementMap = this.omRestService.call(sessionURL, null);
Element item = (Element)elementMap.get("return");
setSessionId(item.elementText("session_id"));
log.info(item.elementText("session_id"));
result = this.omRestService.call("http://" + url + ":" + port +
"/openmeetings/
services/UserService/loginUser?SID=" + getSessionId() + "&username=" +
omusername
+ "&userpass=" + userpass, null);
if
(Integer.valueOf(((Element)result.get("return")).getStringValue()).intValue() >
) {
return Boolean.valueOf(true);
}
return Boolean.valueOf(false);
}
public Long addRoomWithModerationExternalTypeAndTopBarOption(Boolean
isAllowedRecording,
Boolean isAudioOnly, Boolean isModeratedRoom, String name, Long
numberOfParticipent, Long
roomType, String externalRoomType)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services/
RoomService/addRoomWithModerationExternalTypeAndTopBarOption?" +
"SID=" + getSessionId() +
"&name=" + name +
"&roomtypes_id=" + roomType.toString() +
"&comment=jira" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&externalRoomType=" + externalRoomType +
"&allowUserQuestions=" +
"&isAudioOnly=" + isAudioOnly.toString() +
"&waitForRecording=false" +
"&allowRecording=" + isAllowedRecording.toString() +
"&hideTopBar=false";
LinkedHashMap result = this.omRestService.call(restURL, null);
roomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(roomId);
}
public Long updateRoomWithModerationAndQuestions(Boolean isAllowedRecording,
Boolean
isAudioOnly, Boolean isModeratedRoom, String roomname, Long
numberOfParticipent, Long
roomType, Long roomId)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String updateRoomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/RoomService/
updateRoomWithModerationAndQuestions?" +
"SID=" + getSessionId() +
"&room_id=" + roomId.toString() +
"&name=" + roomname.toString() +
"&roomtypes_id=" + roomType.toString() +
"&comment=" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&allowUserQuestions=";
LinkedHashMap result = this.omRestService.call(restURL, null);
log.info("addRoomWithModerationExternalTypeAndTopBarOption with ID: ",
((Element)result.get("return")).getStringValue());
updateRoomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(updateRoomId);
}
public String setUserObjectAndGenerateRoomHash(String username, String
firstname, String
lastname, String profilePictureUrl, String email, String externalUserId, String
externalUserType, Long room_id, int becomeModeratorAsInt, int
showAudioVideoTestAsInt)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomHash = null;
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/UserService/
setUserObjectAndGenerateRoomHash?" +
"SID=" + getSessionId() +
"&username=" + username +
"&firstname=" + firstname +
"&lastname=" + lastname +
"&profilePictureUrl=" + profilePictureUrl +
"&email=" + email +
"&externalUserId=" + externalUserId +
"&externalUserType=" + externalUserType +
"&room_id=" + room_id +
"&becomeModeratorAsInt=" + becomeModeratorAsInt +
"&showAudioVideoTestAsInt=" + showAudioVideoTestAsInt;
LinkedHashMap result = this.omRestService.call(restURL, null);
roomHash = ((Element)result.get("return")).getStringValue();
return roomHash;
}
public String getSessionId() {
return this.sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
I want to call loginuser method from OmGateway class on Jsp Button Click Event. Kindly help me to solve this Error. And Help To Redirect and Integrate to openmeetings. Thank you In Advance.
Visit Atlassian Developers for help
Have you ever tried the Jira Plugin from the website:
http://openmeetings.apache.org/JiraPlugin.html
or is this actually the plugin code that you are posting here?
I am puzzled, I have a call with jQuery using .load to fill a DIV with content composed of transformed XML into HTML, but whenever I call load (or $.get or $.ajax for that matter) I get a "400 Bad Request - The request sent by the client was syntactically incorrect" message.
The parameters are all there and even when I set up a test call for a page with no parameters I get the same message. All this is being done via Spring (v3) with an annotated controller. What's confusing is that I already have a portion of this working with calls to a web service that return a JSON object to fill a SELECT and that works fine.
How do I fill the DIV with HTML?
Javascript jQuery call:
function doSearch()
{
var sUrl = "query.html";
var sSecurityToken = '?st=' + $('#ihSecurityToken').val();
var sProjects = '';
$("#sltProjects option:selected").each(function ()
{
sProjects += $(this).val() + ';';
});
sProjects = '&pn=' + escape(sProjects);
var sDatabases = '';
$("#sltDatabases option:selected").each(function ()
{
sDatabases += $(this).val() + ';';
});
sDatabases = '&db=' + escape(sDatabases);
var sQueryText = '&qt=' + escape($('#taSearchText').val());
sSort = '&sr=' + $('#sltSort').val();
sResultsPerPage = '&rp=' + $('#sltResultsPerPage').val();
sRelevance = '&rl=' + $('#sltRelevance').val();
var sFilters = '&ft=';
var sTemp = '';
$("[id^=fld]").each( function()
{
sName = $(this).attr('alt');
sValue = escape($(this).val());
sTemp += escape((sName + '=' + sValue + ';'));
});
if (sTemp.length)
{
sFilters += sTemp;
}
else
{
sFilters = '';
}
var sStartingPage = "&sp=1";
sFinal = sUrl + sSecurityToken + sProjects + sDatabases + sQueryText + sSort + sResultsPerPage + sRelevance + sFilters + sStartingPage;
$('#resultsBlock').load(sFinal);
}
Controller code:
package enterprisesearch.web;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.SAXException;
import enterprisesearch.domain.DatabaseFilter;
import enterprisesearch.domain.UserDatabaseProject;
import enterprisesearch.domain.service.DouglasService;
/**
* #author bob
*
*/
#Controller
public class SearchController
{
protected final Log logger = LogFactory.getLog(getClass());
private DouglasService dgWebService = new DouglasService("http://localhost:8080/Douglas/services/Douglas");
#RequestMapping("/search.html")
#ModelAttribute("message")
public String getMessage()
{
return "Results go here...";
}
#ModelAttribute("username")
public String getUsername(#RequestParam(value="username", required=true) String psUsername)
{
return psUsername;
}
#ModelAttribute("securitytoken")
public String getSecurityToken(#RequestParam(value="username", required=true) String psUsername)
{
String sReturn = "";
Map<String, String> mpResult = this.dgWebService.getSecurityToken(psUsername);
if (mpResult.containsValue("SUCCESS"))
{
sReturn = mpResult.get("securityinfo");
}
else
{
sReturn = mpResult.get("errorid");
}
return sReturn;
}
#ModelAttribute("userprojects")
public Collection<UserDatabaseProject> getUserProjects(#RequestParam(value="username", required=true) String psUsername) throws ParserConfigurationException, SAXException, IOException
{
String sUsername = "";
if (psUsername == null || psUsername.isEmpty())
{
sUsername = "lymana";
}
else
{
sUsername = psUsername;
}
return this.dgWebService.getUserDatabaseProjects(sUsername);
}
#RequestMapping("/databases.html")
public #ResponseBody Map<String, String> getUserDatabases(#RequestParam(value="username", required=true) String psUsername, #RequestParam(value="projectname", required=true) String psProjectName) throws ParserConfigurationException, SAXException, IOException
{
Map<String, String> mpDatabases = new HashMap<String, String>();
Collection<UserDatabaseProject> udpProjects = this.dgWebService.getUserDatabaseProjects(psUsername);
if (udpProjects.size() > 0)
{
for (UserDatabaseProject udpProject : udpProjects)
{
if (psProjectName.indexOf(udpProject.get_msProjectName()) != -1)
{
mpDatabases.put(udpProject.get_msDatabaseName(), udpProject.get_msDatabaseDescription());
}
}
}
else
{
mpDatabases.put("","No databases were found for the selected project");
}
return mpDatabases;
}
#RequestMapping("/filters.html")
public #ResponseBody Map<String, String> getCommonDBFilters(#RequestParam(value="databases", required=true) String psDatabaseNames) throws ParserConfigurationException, SAXException, IOException
{
Map<String, String> mpDatabases = new HashMap<String, String>();
Collection<DatabaseFilter> dfFilters = this.dgWebService.getCommonDBFilters(psDatabaseNames);
if (dfFilters.size() > 0)
{
for (DatabaseFilter dfFilter : dfFilters)
{
if (psDatabaseNames.indexOf(dfFilter.get_msDatabaseName()) != -1)
{
mpDatabases.put(dfFilter.get_msFilterName(), dfFilter.get_msFilterName());
}
}
}
else
{
mpDatabases.put("","No filters were found for the selected database(s)");
}
return mpDatabases;
}
#RequestMapping("/test.html")
public ModelAndView execTest()
{
//Map<String, String> mpDatabases = new HashMap<String, String>();
ModelAndView mavReturn = new ModelAndView("test.jsp");
//mpDatabases.put("test","<b>No filters were found for the selected database(s)</b>");
return mavReturn;
}
//#ModelAttribute("searchResults")
/* #RequestMapping(value = "/query.html", method = RequestMethod.GET)
public ModelAndView doSearch(#RequestParam(value="st", required=true) String psSecurityToken,
#RequestParam(value="pn", required=true) String psProjects,
#RequestParam(value="db", required=true) String psDatabases,
#RequestParam(value="qt", required=true) String psQueryText,
#RequestParam(value="sr", required=true) String psSort,
#RequestParam(value="rp", required=true) String psResultsPerPage,
#RequestParam(value="rl", required=true) String psRelevance,
#RequestParam(value="sp", required=true) String psStartingPage,
#RequestParam(value="ft", required=false) String psFilters)
{
ModelAndView mavReturn = new ModelAndView("query.jsp");
String sTemp = "";
String sOptions = "";
String sStartingPage = "1";
if (!psStartingPage.isEmpty())
{
sStartingPage = psStartingPage;
}
String sSort = "Sort=" + psSort;
String sResultsPerPage = "ResultsStart=" + sStartingPage + ";ResultsEnd=" + psResultsPerPage;
String sDatabases = "Repositories=" + psDatabases.replace(';', ',');
String sRelevance = "RelevanceMin=" + psRelevance;
String sDefaults = "Print=All;SummaryType=Context;Highlighting=Terms+SummaryTerms;";
sOptions = sSort + ";" + sResultsPerPage + ";" + sDatabases + ";" + sRelevance + ";" + sDefaults;
//sReturn = this.dgWebService.executeTextQuery(psSecurityToken, psProjects, psDatabases, psQueryText, sOptions, psFilters);
sTemp = "<b>This is a test</b>";
mavReturn.addObject("searchResults", sTemp);
return mavReturn;
}*/
/*#RequestMapping(value = "/test.html", method = RequestMethod.GET)
public ModelAndView doTest(#RequestParam(value="st", required=true) String psSecurityToken)
{
String sTemp = "";
ModelAndView mavReturn = new ModelAndView("test.jsp");
//sReturn = this.dgWebService.executeTextQuery(psSecurityToken, psProjects, psDatabases, psQueryText, sOptions, psFilters);
sTemp = "<b>This is a test</b>";
mavReturn.addObject("searchResults", sTemp);
return mavReturn;
}*/
}
URL:
http://localhost:8085/EnterpriseSearch/query.html?st=kjahsdf9845hasfha9348uwhefas&pn=ECC%3B&db=dbECC%3B&qt=money&sr=relevance&rp=10&rl=90&sp=1&ft=false
Firebug info:
Response Headersview source
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 971
Date Thu, 03 Nov 2011 20:06:56 GMT
Connection close
Request Headersview source
Host localhost:8085
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.23) Gecko/20110920 Firefox/3.6.23
Accept text/html, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://localhost:8085/EnterpriseSearch/search.html?username=lymana
Cookie JSESSIONID=CC30B029E8C9215489D4F938A6C1BB9D
Any ideas? What am I missing?
Updated to include the complete Controller code.
I copied and pasted your Java code into my Spring 3.0 testing application, and hit that URL manually. If you hit that URL directly, do you get the same 400?
There are a few simple problems I could see happening, but you've most likely already ruled them out.. I just don't have enough info reading your message to know!
Do you have a view that matches the string that you're returning from the RequestMapped function?
Is it even calling that doSearch function(), if you add a trace message to it?
Is there anything at all in your error logs?
What does your access log say?