ObjectMapper readValue Fail - java

I want to make a UserUtil to auto make User and get the User's mobile and cookie in the txt file.
I finished auto insert the User's information into the mysql,but I can't auto write it into the txt file.
The main code about this:
public class UserUtil {
private static void createUser(int count) throws Exception {
// the code about insert into database not show here
// login,get the cookie
String urlString = "http://localhost:8080/login/toLogin";
File file = new File("my file location");
if (file.exists()) {
file.delete();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
for (int i = 0; i < users.size(); i++) {
User user = users.get(i);
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream out = httpURLConnection.getOutputStream();
String params = "mobile=" + user.getId() + "&password=" + MD5Util.inputPassToFormPass("123456");
// the params I test show the first line in database,such as mobile=1300000000&password=d3b1294a61a07da9b49b6e22b2cbd7f9
System.out.println(params);
out.write(params.getBytes());
out.flush();
InputStream inputStream = httpURLConnection.getInputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = inputStream.read(buff)) >= 0) {
bout.write(buff, 0, len);
}
inputStream.close();
bout.close();
String response = new String(bout.toByteArray
// I test the response print my login.html content
System.out.println(response);
ObjectMapper mapper = new ObjectMapper();
RespBean respBean = mapper.readValue(response,RespBean.class);
String userCookie = ((String) respBean.getObj());
System.out.println("create userCookie : " + user.getId());
String row = user.getId() + "," + userCookie;
raf.seek(raf.length());
raf.write(row.getBytes());
raf.write("\r\n".getBytes());
System.out.println("write to file :" + user.getId());
}
raf.close();
System.out.println("over");
}
}
I run it , the error is:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (String)"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<!-- jquery -->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<!-- bootstrap -->
<link rel="stylesheet" type="text/css"
href="/bootstrap/css/bootstrap.min.css"/>
<script type="text/javascript" src="/bootstrap/js/bootstrap.min.js">
</script>
<!-- jquery-validator -->
<script type="text/javascript" src="/jquery-validation/jquery.validate"[truncated 2917 chars]; line: 1, column: 2]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1851)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:707)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:632)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:1947)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:776)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4664)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4513)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3468)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3436)
at com.example.demo.utils.UserUtil.createUser(UserUtil.java:85)
at com.example.demo.utils.UserUtil.main(UserUtil.java:108)
the UserUtil.java:85 is this line:
RespBean respBean = mapper.readValue(response,RespBean.class);
my RespBean :
package com.example.demo.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
#AllArgsConstructor
public class RespBean {
private long code;
private String message;
private Object obj;
/**
* Success
* #return
*/
private static RespBean success(){
return new RespBean(RespBeanEnum.SUCCESS.getCode(),RespBeanEnum.SUCCESS.getMessage(),null);
}
public static RespBean success(Object obj){
return new RespBean(RespBeanEnum.SUCCESS.getCode(),RespBeanEnum.SUCCESS.getMessage(),obj);
}
/**
* Fail
* #param respBeanEnum
* #return
*/
public static RespBean error(RespBeanEnum respBeanEnum){
return new RespBean(respBeanEnum.getCode(),respBeanEnum.getMessage(),null);
}
public static RespBean error(RespBeanEnum respBeanEnum,Object obj){
return new RespBean(respBeanEnum.getCode(),respBeanEnum.getMessage(),obj);
}
}
the RespBeanEnum:
#Getter
#ToString
#AllArgsConstructor
public enum RespBeanEnum {
// All
SUCCESS(200,"SUCCESS"),
ERROR(500,"Server error"),
// Login part
LOGIN_ERROR(500210,"username or password error"),
MOBILE_ERROR(500211,"mobile layout error"),
BIND_ERROR(500212,"parameter error"),
;
private final Integer code;
private final String message;
}
and my UserServiceImpl return is no problem
public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
// the login logic code don't show here
// the UUIDUtil is the util to make the cookie
String uuid = UUIDUtil.uuid();
CookieUtil.setCookie(request,response,"userCookie",uuid);
return RespBean.success(uuid);
}

Related

add an error message to panel in apache wicket

I have an apache wicket panel for google recaptcha where I integrate wicket with google recaptcha and everything is working as it should, but I need to add an error message or feedbackpanel I am not quite good with wicket, so please advise me what is the best solution for my case?
public class ReCaptchaPanel extends Panel {
private static final long serialVersionUID = -8346261172610929107L;
private static final Logger log = LoggerFactory.getLogger(ReCaptchaPanel.class);
final String publicKey = "6LdrIgceAAAAADWF-gIz_OHJg_5gLu7IVw11hTnt";
final String secretKey = "6LdrIgceAAAAAE9qxHViBj3Sl8uyqUVdluugPRTq";
final String scriptClassName = "data-sitekey";
final String recCaptchaClassName = "g-recaptcha";
String currentLanguage = getLocale().getLanguage();
String scriptValue = "https://www.google.com/recaptcha/api.js?hl=" + currentLanguage;
/* in the following link you can find the language codes
* https://developers.google.com/recaptcha/docs/language
* */
public ReCaptchaPanel(String id) {
super(id);
final IFeedbackMessageFilter feedbackFilter = new ContainerFeedbackMessageFilter(this);
final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback", feedbackFilter);
feedbackPanel.setOutputMarkupId(true);
add(feedbackPanel);
add(new Label("reCaptchaComponent", "").add(new SimpleAttributeModifier("class", recCaptchaClassName))
.add(new SimpleAttributeModifier(scriptClassName, publicKey)));
add(new Label("reCaptchaScript", "").add(new SimpleAttributeModifier("src", scriptValue)));
}
public ReCaptchaPanel(String id, IModel model) {
super(id, model);
}
/**
* Validates Google reCAPTCHA V2 .
*
* #param secretKey Secret key (key given for communication between arena and Google)
* #param response reCAPTCHA response from client side (g-recaptcha-response).
* #return true if validation successful, false otherwise.
*/
public synchronized boolean isCaptchaValid(String secretKey, String response) {
try {
String url = "https://www.google.com/recaptcha/api/siteverify",
params = "secret=" + secretKey + "&response=" + response;
HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
OutputStream out = http.getOutputStream();
out.write(params.getBytes(StandardCharsets.UTF_8));
out.flush();
out.close();
InputStream res = http.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(res, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
JSONObject json = new JSONObject(sb.toString());
res.close();
log.info("Google ReCaptcha has been verified");
return json.getBoolean("success");
} catch (Exception e) {
e.printStackTrace();
}
log.error(" Google ReCaptcha failed");
return false;
}
public synchronized boolean isCaptchaValid() {
HttpServletRequest httpServletRequest = ApplicationBase.getHttpServletRequest();
assert httpServletRequest != null;
String response = httpServletRequest.getParameter("g-recaptcha-
response");
return isCaptchaValid(secretKey, response);
}
}
I use this panel in another wicket component ( form) ,
class FormEmail extends Form {
.........
final ReCaptchaPanel reCaptchaPanel = new ReCaptchaPanel("reCaptchaPanel") {
/**
* #see org.apache.wicket.Component#isVisible()
*/
#Override
public boolean isVisible() {
SessionBase session = (SessionBase) getSession();
ItemListPanelConfigParams configParams = new ItemListPanelConfigParams(session);
return configParams.isShowCaptcha();
}
};
add(reCaptchaPanel);
Button buttonSend = new Button("buttonSend") {
#Override
public void onSubmit() {
onSendCallback(emailRecipient, emailReplyTo, comment);
setResponsePage(callbackPage);
}
};
what i need to achieve is that add a message when the verify method in code above is false; I mean an error message, anyone knows how.

How to sent data from form to backend? [Java]

how to send data from the form view to the backend? I want to use the collected data to create a JSON request.
#Controller
public class ControllerClass {
Connect connect = new Connect();
#RequestMapping(value = "/Search", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("Forms", "FlightDTO", new FlightDTO());
}
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect();
}
}
View class collecting data.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/connect}" th:object="${FlightDTO}" method="post">
<p>Orgin: <input type="text" th:field="*{Origin}" /></p>
<p>Departure: <input type="text" th:field="*{Departure}" /></p>
<p>DateFrom: <input type="text" th:field="*{DateFrom}" /></p>
<p>DateTo: <input type="text" th:field="*{DateTo}" /></p>
<p>Currency: <input type="text" th:field="*{Currency}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
Class responsible for consume data JSON.
public class Connect {
public String connect() {
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
URL url = new URL(urlBuilder.ulr());
HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
output = response.toString();
} catch (Exception e) {
System.out.println("Exception Flight:- " + e);
}
return output;
}
}
Class that is responsible for collecting data from the view
public class FlightDTO {
private String dateFrom;
private String dateTo;
#Size(min = 2, max = 10)
private String origin;
#Size(min = 2, max = 10)
private String departure;
#Size(min = 2, max = 4)
private String currency;
My URL builder Class responsible for build request.
public class UrlBuilder extends FlightDTO {
private String key = "47c5ebee552ce27c902e7521b6ef3858";
public String ulr( ) {
String connectUrlString =
"http://api.travelpayouts.com/v1/prices/cheap?origin="
+ getOrigin() + "&destination=" + getDeparture() +
"&depart_date=" + getDateFrom() +
"&currency=" + getCurrency() +
"&return_date=" + getDateTo() +
"&token=" + key;
return connectUrlString ;
}
}
I tried to solve my problem in many ways. Unfortunately to no avail, that's why I decided to create a thread. I could not find a similar problem. I was probably looking for a bad one. However, I do not know how to google
I get null response :
http://api.travelpayouts.com/v1/prices/cheap?origin=null&destination=null&depart_date=null&currency=null&return_date=null&token=47c5ebee552ce27c902e7521b6ef3858
Above code will not work as you are creating new UrlBuilder object which will not have any values instead of passing flightDTO object from the controller.
Controller
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect(flightDTO); //passing flightDTO object received from form
}
Connect
public String connect(FlightDTO flightDTO) { //Added new parameter to recevice flightDTO
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.setOrigin(flightDTO.getOrigin());
urlBuilder.setDestination(flightDTO.getDestination());
urlBuilder.setDateFrom(flightDTO.getDateFrom());
urlBuilder.setDateTo(flightDTO.getDateTo());
......//Set other required values
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
......//other code
}
}

Scribe-java and Woocommerce authentication

I'm trying to implement support for Woocommerce e-shop into our system and I'm using scribe-java for that. What I'm trying is to get Json response from e-shop and store it into database.
Problem is that I can connect to e-shop but instead of Json response, I get HTML response. Any help would be much appreciated. BTW, I'm using latest scribe-java 3.0.0
URL: http://shop_url/wp-json/wc/v1/orders?after=2016-08-17T00:00:00&page=1&per_page=100&order=asc
Here's source code:
private Integer callGETWithOAuthAuthentication(String url, StringBuffer sbRet) throws IOException {
OAuth10aService service = new ServiceBuilder()
.apiKey(getSettingsStr().getSecret1())
.apiSecret(getSettingsStr().getSecret2())
.debugStream(System.out)
.signatureType(SignatureType.QueryString)
.build(WooCommerceApi.instance());
OAuthRequest request = new OAuthRequest(Verb.GET, url, service);
service.signRequest( new OAuth1AccessToken("", ""), request);
Response response = request.send();
BufferedReader in = new BufferedReader(
new InputStreamReader(response.getStream()));
String inputLine;
StringBuffer responseJson = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseJson.append(inputLine);
}
if (sbRet != null) {
sbRet.append(responseJson.toString());
}
return response.getCode();
}
And here is WooCommerceApi
import com.github.scribejava.core.builder.api.DefaultApi10a;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.services.HMACSha1SignatureService;
import com.github.scribejava.core.services.SignatureService;
public class WooCommerceApi extends DefaultApi10a {
protected WooCommerceApi() {
}
private static class InstanceHolder {
private static final WooCommerceApi INSTANCE = new WooCommerceApi();
}
public static WooCommerceApi instance() {
return InstanceHolder.INSTANCE;
}
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public Verb getAccessTokenVerb() {
return Verb.GET;
}
#Override
public Verb getRequestTokenVerb() {
return Verb.GET;
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
// TODO Auto-generated method stub
return null;
}
#Override
public SignatureService getSignatureService() {
return new HMACSha1SignatureService();
}
}
And this is a response I'm getting:
`<!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" lang="sl-SI">
<![endif]-->
<!--[if IE 7]>
<html id="ie7" lang="sl-SI">
<![endif]-->
<!--[if IE 8]>
<html id="ie8" lang="sl-SI">
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html lang="sl-SI">
<!--<![endif]-->
<head>`

HtmlViewService in OBIEE Web Service API is not rendering report (it's only showing spinning loader)

I have a Java application that leverages the OBIEE Web Service API to consume data from the BI Server. I am able to XMLViewService and the WebCatalogService just fine, but I can't quite get the HtmlViewService to properly render a report in the Java app. The report just shows the spinning loader, but never actually renders the report. I'm pretty sure it has to do with the fact that the Java app and the BI Server are on different domains. This is what the API documentation says:
In situations where Oracle BI Web Services and the third-party Web server do not belong to the same Domain Name Service (DNS) domain, users may get JavaScript errors related to browser security constraints for cross-domain scripting. To avoid these issues, use the setBridge() method to modify callback URLs to point to the third-party Web server. Be aware that a Web component executed by the third-party Web server to re-route requests to Oracle BI Web Services is not provided. This function would need to be fulfilled by the third-party application.
Several years ago, I did this same type of integration using .NET/C# and ran in the the same issue because the .NET app and the BI Server were on different domains. As a result, I had to create an HTTP Handler (.ashx file) as well as use the setBridge() method to to solve the issue.
The challenge that I'm having is that I can't find a servlet bridge example for Java. And I'm not too confident in porting the .NET/.ASHX code to a Java servlet/bridge. Does anyone have any code examples or direction they could provide to point me in the right direction? Here's a snippet of code to show you what I'm doing to pull back the report data:
// define report path
ReportRef reportRef = new ReportRef();
reportRef.setReportPath(reportFolder + "/" + reportName);
// set page params
StartPageParams pageParams = new StartPageParams();
pageParams.setDontUseHttpCookies(true);
// set report params
String pageId = htmlService.startPage(pageParams, sawSessionId);
String reportId = pageId + reportName;
htmlService.addReportToPage(pageId, reportId, reportRef, null, null, null, sawSessionId);
// get report html
StringBuffer reportHtml = new StringBuffer();
reportHtml.append(htmlService.getHtmlForReport(pageId, reportId, sawSessionId));
// return html
return reportHtml.toString();
This is the error that is coming back in the browser:
XMLHttpRequest cannot load http://myobiserver.com/analytics/saw.dll?ajaxGo. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myjavaapp.com' is therefore not allowed access.
Per requested, here is my .NET/.ASHX bridge:
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Web;
using System;
using System.Collections;
using System.Configuration;
using System.Collections.Specialized;
using System.Web;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
/*
This is a ASP.NET handler that handles communication
between the SharePoint site and OracleBI.
It will be deployed to:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\OracleBI
*/
public class OracleBridge: IHttpHandler
{
public bool IsReusable {get{return true;}}
public OracleBridge()
{
}
string getServer()
{
string strServer = "http://<enter-domain>/analytics/saw.dll";
int index = strServer.LastIndexOf("/");//split off saw.dll
if (index >=0)
return strServer.Substring(0,index+1);
else
return strServer;
}
public void ProcessRequest(HttpContext context)
{
HttpWebRequest req = forwardRequest(context);
forwardResponse(context,req);
}
private HttpWebRequest forwardRequest(HttpContext context)
{
string strURL = makeURL(context);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
req.Method = context.Request.HttpMethod;
NameValueCollection headers = context.Request.Headers;
req.Accept = headers.Get("Accept");
req.Expect = headers.Get("Expect");
req.ContentType = headers.Get("Content-Type");
string strModifiedSince = headers.Get("If-Modified-Since");
if (strModifiedSince != null && strModifiedSince.Length != 0)
req.IfModifiedSince = DateTime.Parse(strModifiedSince);
req.Referer = headers.Get("Referer");
req.UserAgent = headers.Get("User-Agent");
if (!req.Method.Equals("GET"))
{
CopyStreams(context.Request.InputStream,req.GetRequestStream());
}
return req;
}
private void forwardResponse(HttpContext context, HttpWebRequest req)
{
HttpWebResponse resp =null;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch(WebException e)
{
resp = (HttpWebResponse)e.Response;
}
context.Response.StatusCode = (int)resp.StatusCode;
for (int i = 0; i < resp.Cookies.Count; i++)
{
Cookie c = resp.Cookies[i];
HttpCookie hc = new HttpCookie(c.Name, c.Value);
hc.Path = c.Path;
hc.Domain = getServer();
context.Response.Cookies.Add(hc);
}
context.Response.ContentType = resp.ContentType;
CopyStreams(resp.GetResponseStream(), context.Response.OutputStream);
}
private string makeURL(HttpContext context)
{
string strQuery = context.Request.Url.Query;
string[] arrParams = strQuery.Split('?','&');
StringBuilder resultingParams = new StringBuilder();
string strURL=null;
foreach(string strParam in arrParams )
{
string[] arrNameValue = strParam.Split('=');
if (!arrNameValue[0].Equals("RedirectURL"))
{
if (strParam.Length != 0)
{
if (resultingParams.Length != 0)
resultingParams.Append("&");
resultingParams.Append(strParam);
}
}
else if (arrNameValue.Length >1)
strURL = HttpUtility.UrlDecode(arrNameValue[1]);
}
if (strURL ==null)
throw new Exception("Invalid URL format. requestURL parameter is missing");
String sAppendChar = strURL.Contains("?") ? "&" : "?";
if (strURL.StartsWith("http:") || strURL.StartsWith("https:"))
{
String tmpURL = strURL + sAppendChar + resultingParams.ToString();
return tmpURL;
}
else
{
String tmpURL = getServer() + strURL + sAppendChar + resultingParams.ToString();
return tmpURL;
}
}
private void CopyStreams(Stream inStr,Stream outStr)
{
byte[] buf = new byte[4096];
try
{
do
{
int iRead = inStr.Read(buf,0,4096);
if (iRead == 0)
break;
outStr.Write(buf,0,iRead);
}
while (true);
}
finally
{
outStr.Close();
}
}
}
Using the BridgeServlet from link (http://pastebin.com/NibVnBLb) posted in previous answer did not work for us. In our web portal, embedding Oracle BI dashboard using BridgeServlet above, redirected us to OBI login page and console log showed incorrect resources(js/css) web links (local URL instead of OBIEE URL's).
Instead we used this class (with some minor adjustments) https://gist.github.com/rafaeltuelho/9376341#file-obieehttpservletbridge-java.
Tested with Java 11, Oracle Business Intelligence 12.2.1.4.0, WSDL v12 of OBIEE (http://OBIEE-server:port/analytics/saw.dll/wsdl/v12), with SSO disabled.
Here it is the BridgeServlet class:
package com.abs.bi;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class OBIEEBridge
*/
public class BridgeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BridgeServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
this.processRequest(request, response);
} catch (Exception e) {
throw new ServletException(e);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
this.processRequest(request, response);
} catch (Exception e) {
throw new ServletException(e);
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpURLConnection urlCon = forwardRequest(request);
forwardResponse(response, urlCon);
}
#SuppressWarnings("unchecked")
private String decodeURL(HttpServletRequest request) {
StringBuffer bufURL = new StringBuffer("");
Map<String, String[]> params = request.getParameterMap();
String[] arrURL = params.get("RedirectURL");
String strURL = arrURL == null || arrURL.length == 0 ? null : arrURL[0];
bufURL.append(strURL);
int nQIndex = strURL.lastIndexOf('?');
if (params != null && !params.isEmpty()) {
bufURL.append(((nQIndex >= 0) ? "&" : "?"));
Set<String> keys = params.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
try {
String strKey = it.next();
if (strKey.equalsIgnoreCase("RedirectURL")) {
continue;
}
String strEncodedKey = URLEncoder.encode(strKey, "UTF-8");
String[] paramValues = params.get(strKey);
for (String paramValue : paramValues) {
bufURL.append(strEncodedKey);
bufURL.append("=");
bufURL.append(URLEncoder.encode(paramValue, "UTF-8"));
bufURL.append("&");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
bufURL.deleteCharAt(bufURL.length() - 1);
}
return bufURL.toString();
}
#SuppressWarnings("unchecked")
private HttpURLConnection forwardRequest(HttpServletRequest request) throws IOException {
String strURL = decodeURL(request);
String[] arrURL = strURL.split("&", 2);
String baseURL = arrURL[0];
URL url = new URL(baseURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String strMethod = request.getMethod();
con.setRequestMethod(strMethod);
Enumeration<String> en = request.getHeaderNames();
String strHeader;
while (en.hasMoreElements()) {
strHeader = en.nextElement();
String strHeaderValue = request.getHeader(strHeader);
con.setRequestProperty(strHeader, strHeaderValue);
}
// is not a HTTP GET request
if (strMethod.compareTo("GET") != 0) {
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
DataOutputStream forwardStream = new DataOutputStream(con.getOutputStream());
try {
String urlParameters = arrURL[1];
forwardStream.writeBytes(urlParameters);
forwardStream.flush();
} finally {
forwardStream.close();
}
}
return con;
}
private void forwardResponse(HttpServletResponse response, HttpURLConnection con) throws IOException {
int nContentLen = -1;
String strKey;
String strValue;
try {
response.setStatus(con.getResponseCode());
for (int i = 1; true; ++i) {
strKey = con.getHeaderFieldKey(i);
strValue = con.getHeaderField(i);
if (strKey == null) {
break;
}
if (strKey.equals("Content-Length")) {
nContentLen = Integer.parseInt(con.getHeaderField(i));
continue;
}
if (strKey.equalsIgnoreCase("Connection") || strKey.equalsIgnoreCase("Server")
|| strKey.equalsIgnoreCase("Transfer-Encoding") || strKey.equalsIgnoreCase("Content-Length")) {
continue; // skip certain headers
}
if (strKey.equalsIgnoreCase("Set-Cookie")) {
String[] cookieStr1 = strValue.split(";");
String[] cookieStr2 = cookieStr1[0].split("=");
// String[] cookieStr3 = cookieStr1[1].split("=");
/*
* Change the Set-Cookie HTTP Header to remove the 'path' attribute. Thus the
* browser can accept the ORA_BIPS_NQID cookie from Oracle BI Server
*/
Cookie c = new Cookie(cookieStr2[0], cookieStr2[1]);
c.setPath("/");
response.addCookie(c);
} else {
response.setHeader(strKey, strValue);
}
}
copyStreams(con.getInputStream(), response.getOutputStream(), nContentLen);
} finally {
response.getOutputStream().close();
con.getInputStream().close();
}
}
private void copyStreams(InputStream inputStream, OutputStream forwardStream, int nContentLen) throws IOException {
byte[] buf = new byte[1024];
int nCount = 0;
int nBytesToRead = 1024;
int nTotalCount = 0;
do {
if (nContentLen != -1)
nBytesToRead = nContentLen - nTotalCount > 1024 ? 1024 : nContentLen - nTotalCount;
if (nBytesToRead == 0)
break;
// try to read some bytes from src stream
nCount = inputStream.read(buf, 0, nBytesToRead);
if (nCount < 0)
break;
nTotalCount += nCount;
// try to write some bytes in target stream
forwardStream.write(buf, 0, nCount);
} while (true);
}
}
AbsServiceUtils which contains SAWSessionService and HtmlViewService web service calls to Oracle BI server:
package com.abs.bi;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import oracle.bi.web.soap.AuthResult;
import oracle.bi.web.soap.HtmlViewService;
import oracle.bi.web.soap.HtmlViewServiceSoap;
import oracle.bi.web.soap.ReportHTMLLinksMode;
import oracle.bi.web.soap.ReportHTMLOptions;
import oracle.bi.web.soap.ReportRef;
import oracle.bi.web.soap.SAWLocale;
import oracle.bi.web.soap.SAWSessionParameters;
import oracle.bi.web.soap.SAWSessionService;
import oracle.bi.web.soap.SAWSessionServiceSoap;
import oracle.bi.web.soap.StartPageParams;
public class AbsServiceUtils {
private AbsServiceUtils() {
}
public static URL buildWsdlUrl() throws MalformedURLException {
return new URL(IAbsService.BASEWSDLURL);
}
public static void writeBiContent(HttpServletRequest request, JspWriter out, String biReport) throws IOException {
String userAgent = request.getHeader("User-Agent");
Locale userLocale = request.getLocale();
String bridgeServletContextPath = request.getContextPath() + "/bridgeservlet";
String reportHtml = writeBiContent(biReport, userAgent, userLocale, bridgeServletContextPath);
if (out != null) {
out.println(reportHtml);
}
}
public static String writeBiContent(String biReport, String userAgent, Locale userLocale,
String bridgeServletContextPath) throws MalformedURLException {
HtmlViewService htmlViewService = new HtmlViewService(buildWsdlUrl());
HtmlViewServiceSoap htmlClient = htmlViewService.getHtmlViewService();
SAWSessionService sAWSessionService = new SAWSessionService(buildWsdlUrl());
SAWSessionServiceSoap myPort = sAWSessionService.getSAWSessionServiceSoap();
SAWSessionParameters sessionparams = new SAWSessionParameters();
sessionparams.setUserAgent(userAgent);
SAWLocale sawlocale = new SAWLocale();
sawlocale.setLanguage(userLocale.getLanguage());
sawlocale.setCountry(userLocale.getCountry());
sessionparams.setLocale(sawlocale);
sessionparams.setAsyncLogon(false);
AuthResult result = myPort.logonex(IAbsService.BIUSERNAME, IAbsService.BIPASSWORD, sessionparams);
String sessionID = result.getSessionID();
List<String> keepAliveSessionList = new ArrayList<>(1);
keepAliveSessionList.add(sessionID);
myPort.keepAlive(keepAliveSessionList);
StartPageParams spparams = new StartPageParams();
spparams.setDontUseHttpCookies(true);
String pageID = htmlClient.startPage(spparams, sessionID);
/**
* This method will set the path to the servlet which will act like a bridge to
* retrieve all the OBIEE resources like the javascript, CSS and the report.
*/
if (bridgeServletContextPath != null) {
htmlClient.setBridge(bridgeServletContextPath, sessionID);
}
ReportHTMLOptions htmlOptions = new ReportHTMLOptions();
htmlOptions.setEnableDelayLoading(false);
htmlOptions.setLinkMode(ReportHTMLLinksMode.IN_PLACE.value());
ReportRef reportref = new ReportRef();
reportref.setReportPath(IAbsService.BIROOTPATH + biReport);
StartPageParams startpageparams = new StartPageParams();
startpageparams.setDontUseHttpCookies(false);
htmlClient.addReportToPage(pageID, biReport.replace(" ", ""), reportref, null, null, htmlOptions, sessionID);
String reportHtml = htmlClient.getHeadersHtml(pageID, sessionID);
reportHtml = reportHtml + htmlClient.getHtmlForReport(pageID, biReport.replace(" ", ""), sessionID);
reportHtml = reportHtml + htmlClient.getCommonBodyHtml(pageID, sessionID);
return reportHtml;
}
}
IAbsService:
package com.abs.bi;
public interface IAbsService {
public static final String BASEWSDLURL = "http://<OracleBIServer:port>/analytics/saw.dll/wsdl/v12";
public static final String BIUSERNAME = "USER";
public static final String BIPASSWORD = "PASS";
public static final String BIROOTPATH = "/shared/sharedfolder/";
public static final String BIREPORTNAME = "report";
}
Use the link http://pastebin.com/NibVnBLb to check out the bridge code for java. Hope this might be helful.

Pass values from javascript to Servlet [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I'm new bee working on passing below data from jquery to Servlet. Below are my files
javascript:
<script type="text/javascript">
function getData(tableName)
{
var tableId =tableName+"Table";
jsonObj = [];
$(\'#' + tableId + '\').find(\'tbody>tr\').each(function (i) {
var $tds = $(this).find('td'), setvilId = $tds.eq(1).text(),setvilNotes = $tds.eq(8).text();
item = {};
item["id"] = setvilId;
item["notes"] = setvilNotes;
jsonObj.push(item);
});
console.log(jsonObj);
var jsonString =JSON.stringify(jsonObj);
request(jsonString);
};
</script>
<script type=\"text/javascript\">
function updateNotes () {
var editable = true;
var editables = $('td[id*=notestd], td[id*=eta]');
editables.attr('contentEditable', editable);
}
function request(jsonString) {
$.ajax({
url: "/updatesetvil",
type: "POST",
data: jsonString,
dataType: "text",
success: function(){
alert(\"success\");
},
error:function(){
alert(\"failure\");
}
});
};
</script>
Servlet:
public class UpdateSetvil extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
List<SetvilJsonAttributes> setvilAttrs = new LinkedList<SetvilJsonAttributes>();
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Inside servlet");
// 1. get received JSON data from request
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
if(br != null){
json = br.readLine();
}
System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Class
SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);
// 4. Set response type to JSON
response.setContentType("application/json");
setvilAttrs.add(setvilatt);
for (int i=0;i< setvilatt.size(); i++) {
System.out.println(setvilatt.get(i).getId());
}
}
private class SetvilJsonAttributes {
Integer id;
String notes;
String eta;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getEta() {
return eta;
}
public void setEta(String eta) {
this.eta = eta;
}
}
}
Error: java.io.IOException: Error parsing JSON request string
I kindly request anyone to help me on this.I have been stuck and unable to proceed further.
try this,
$.ajax({
url: "/updatesetvil",
type: "POST",
// The key needs to match your method's input parameter (case-sensitive).
data: { jsonString: jsonString},
contentType: "application/json; charset=utf-8"
dataType: "text",
success: function(data){
alert(\"success\"+data);
},
error:function(){
alert(\"failure\"+data);
}
});
Suggestion
If you are getting issues while parsing a JSON string then I can help you to parse the JSON string into Java object using GSON library as illustrated in below sample code.
Please note id should be String otherwise it will result into NumberFormatException for empty id values.
Sample code:
class SetvilJsonAttributes {
private String id;
private String notes;
// getter & setter
}
String jsonString="[{\"id\":\"\",\"notes\":\"\"},{\"id\":\"18001\",\"notes\":\"fdafd\"},{\"id\":\"8350\",\"notes\":\"daggda\"},{\"id\":\"8056\",\"notes\":\"gfdagdfa\"}]";
Type type = new TypeToken<ArrayList<SetvilJsonAttributes>>() {}.getType();
ArrayList<SetvilJsonAttributes> data = new Gson().fromJson(jsonString,type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
output:
[
{
"id": "",
"notes": ""
},
{
"id": "18001",
"notes": "fdafd"
},
{
"id": "8350",
"notes": "daggda"
},
{
"id": "8056",
"notes": "gfdagdfa"
}
]
If you don't want to change the type of id field then you can try with JsonDeserializer to deserializer it as per your need.
Please have a look at my another posts here and here for JsonDeserializer.
See these three lines:
System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
ObjectMapper mapper = new ObjectMapper();
SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);
The value of json is a JSON array. But, then you map it to SetvilJsonAttributes, which does not support JSON array. You can convert this json to a List of SetvilJsonAttributes using:
ObjectMapper mapper = new ObjectMapper();
ArrayList<SetvilJsonAttributes> setvilatt = mapper.readValue(json, new TypeReference<ArrayList<SetvilJsonAttributes>>(){});
I have used JSONArray and it worked out
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Inside servlet");
Connection connector = MysqlConnector.getDBCon();
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
json = sb.toString();
} catch (Exception e) {
System.out.println("Exception while reading JSON String");
e.printStackTrace();
}
System.out.println("String is " + json);
try {
JSONArray inputArray = new JSONArray(json);
for (int i=0; i < inputArray.length(); i++) {
JSONObject c = inputArray.getJSONObject(i);
String id = c.getString("id");
String notes = c.getString("notes");
System.out.println(id + "--> " + notes);
} catch (JSONException e) {
// crash and burn
System.out.println("Parse exeception for array");
e.printStackTrace();
}
}

Categories

Resources