addAttachment error in XML-RPC while using Java - java

My Java code
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Vector;
import helma.xmlrpc.*;
public class test {
private final static String server_url =
"http://confluence.xyz.com:8080/rpc/xmlrpc";
public static void main (String [] args) {
try {
XmlRpcClient server = new XmlRpcClient(server_url);
Vector<Object> params = new Vector<Object>(2);
params.add("user");
params.add("pass");
String token = (String) server.execute("confluence2.login", params );
System.out.println(token);
Vector<Object> page = new Vector<Object>(3);
page.add(token);
page.add("~username");
page.add("test_page");
Object token1 = server.execute("confluence2.getPage", page );
System.out.println(token1.hashCode());
String fileName = "C:/New folder/a.jpeg";
String contentType = "image/jpeg";
Vector<Object> attachment = new Vector<Object>(2);
attachment.add("a.jpeg");
attachment.add(contentType);
System.out.println(attachment);
byte[] bytes = Files.readAllBytes(Paths.get(fileName));
System.out.println(bytes);
Vector<Object> attach = new Vector<Object>(4);
attach.add(token);
attach.add(token1.hashCode());
attach.add(attachment);
attach.add(bytes);
System.out.println(attach);
server.execute("confluence2.addAttachment", attach);
}
catch (Exception exception) {
System.err.println("JavaClient: " + exception.toString());
}
}
}
Everything works fine except on line where "addAttachment" is called,
error i get is
JavaClient: helma.xmlrpc.XmlRpcException: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy2104.addAttachment(java.lang.String, int, java.util.Vector, [B)
can anyone help me with any other library which i should be using. it seems helma.xmlrpc doesn't have addAttachment method

I used org.apache.xmlrpc.client.XmlRpcClient and not helma but the concepts should be the same. It's not that "helma.xmlrpc doesn't have addAttachment method", it's just that you're calling addAttachment() with the wrong parameters. Try calling it with the proper parameters listed at https://developer.atlassian.com/confdev/confluence-rest-api/confluence-xml-rpc-and-soap-apis/remote-confluence-methods
addAttachment(String token, long contentId, Attachment attachment, byte[] attachmentData)
so for apache xmlrpc, my partial code looks like:
//add attachment to the page
byte[] bytes = FileUtils.readFileToByteArray(new File(FILE_TO_ATTACH));
Map<String, String> attachInfo = new HashMap<String, String>();
attachInfo.put("fileName", FILENAME);
attachInfo.put("contentType", CONTENT_TYPE);
attachInfo.put("comment", COMMENT);
//actually add it now
client.execute("confluence1.addAttachment", new Object[]{token, PAGEID, attachInfo, bytes});

Related

How to List all Public_Ids in Cloudinary using Cloudinary API?

I have tried my best to make this code work but, Alas! Something is definitely wrong. I am tried to list all public_ids in Cloudinary. but it always prints, null. Below is the code -
import java.util.HashMap;
import java.util.Map;
import com.cloudinary.Api;
import com.cloudinary.Cloudinary;
import com.cloudinary.utils.ObjectUtils;
public class AllResources {
#SuppressWarnings("unchecked")
public static void main(String[] Args) {
Map<String, String> config = new HashMap<>();
config.put("cloud_name", "*******");
config.put("api_key", "**************");
config.put("api_secret", "***************************");
Cloudinary c = new Cloudinary(config);
Api api = c.api();
try {
Map<String, Object> result = api.resources(ObjectUtils.asMap());
System.out.println(result.get("public_id"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can do something like the following:
String nextCursor = null;
do {
result = api.resources(ObjectUtils.asMap("max_results", 500, "next_cursor", nextCursor));
nextCursor = result.get("next_cursor");
for (Map.Entry<String, Object> data : result.entrySet()) {
String key = data.getKey().toString();
Object value = data.getValue();
System.out.println(key + value);
}
} while (nextCursor != null);
Itay's code is pseudo code / won't compile. Here is a working version:
Cloudinary cloudinaryApi = new Cloudinary(
ObjectUtils.asMap(
"cloud_name", "YOUR CLOUD NAME",
"api_key", "YOUR API KEY",
"api_secret", "YOUR SECRET KEY"));
ApiResponse result = null;
String nextCursor = null;
do {
try {
result = cloudinaryApi.api().resources(ObjectUtils.asMap("max_results", 500, "next_cursor", nextCursor));
nextCursor = result.containsKey("next_cursor") ? result.get("next_cursor").toString() : null;
if(result.containsKey("resources")) {
List<Map<String,Object>> resources = (ArrayList<Map<String,Object>>) result.get("resources");
for (Map<String,Object> resource : resources) {
if(resource.containsKey("public_id")) {
String publicId = resource.get("public_id").toString();
System.out.println(publicId);
}
}
}
}
catch (Exception e) {
nextCursor = null;
LOG.error(e.getMessage());
}
} while (nextCursor != null);

How to check if byte array is empty or not?

I am using following code to get uploaded file.
#POST
#Path("update")
#Consumes(MediaType.WILDCARD)
public boolean updateWorkBookMaster(MultipartFormDataInput input) {
try {
//get form data
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
//get uploaded file
List<InputPart> inputParts = uploadForm.get("workBookFile");
MultivaluedMap<String, String> header = inputParts.get(0).getHeaders();
InputStream inputStream = inputParts.get(0).getBody(InputStream.class, null);
byte[] bytes = IOUtils.toByteArray(inputStream);
now i want to check whether this byte[] is empty or not,
while debugging when i have not uploaded any file it shows its length as 9, why its 9 not 0.
You can implement null check for files this way:
import org.glassfish.jersey.media.multipart.ContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
#POST
#Path("update")
#Consumes(MediaType.WILDCARD)
public boolean updateWorkBookMaster(FormDataMultiPart multiPartData) {
try {
final FormDataBodyPart workBookFilePart = multiPartData.getField("workBookFile");
final ContentDisposition workBookFileDetails = workBookFilePart.getContentDisposition();
final InputStream workBookFileDocument = workBookFilePart.getValueAs(InputStream.class);
if (workBookFileDetails.getFileName() != null ||
workBookFileDetails.getFileName().trim().length() > 0 ) {
// file is present
} else {
// file is not uploadded
}
} ... // other code
}

Java JSON recovers only one item

In a desktop software, the user is available to presh a button and refresh the "database".
All the info is provided by an online service which returns JSON responses, those responses are saved into DAT files and then parsed with http://www.json.org/java/index.html in order to be saved into in-memory variables as String. The DAT files are only for break-exception-support.
Ok, so I'd created a SwingWorker class which should:
parse the content from the in-memory variable
iterate through elements
recover items
update a progress bar
This is an example of the JSON code:
{
"key":"value",
"data":{
"Name1":{...},
"Name2":{...},
[...]
}
}
The full iteration of the "data" element will create a List, which I must use to create a JTable and populate the main frame of the GUI. But when executing the SwingWorker, it only returns a List which all elements are the last item of the JSON.
Here's the code the SwingWorker:
package com.wolfchamane.lolapi;
import com.wolfchamane.logging.LoCLogger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import org.json.JSONArray;
import org.json.JSONObject;
public class LoLChampions extends SwingWorker{
private static List<LoLChampion> _list;
private static JProgressBar _status;
private static LoCLogger _log;
private static String _exePath;
private static String _version;
private static LoLDDBB _ddbb;
//private static int _max;
public List<LoLChampion> getDataTable(){
return _list;
}
public LoLChampions(){}
public LoLChampions(JProgressBar status){
this();
_status = status;
}
public LoLChampions(JProgressBar status, LoCLogger log){
this(status);
_log = log;
}
public LoLChampions(JProgressBar status, LoCLogger log, String path){
this(status, log);
_exePath = path;
}
public LoLChampions(JProgressBar status, LoCLogger log, String path, LoLDDBB ddbb){
this(status, log, path);
_ddbb = ddbb;
}
public LoLChampions(JProgressBar status, LoCLogger log, String path, LoLDDBB ddbb, String version) throws Exception{
this(status, log, path, ddbb);
_version = version;
}
#Override
protected Object doInBackground() throws Exception {
getChampionsInfo(_ddbb.getJSONChampions());
return true;
}
public void getChampionsInfo(JSONObject jsonChampions) throws Exception{
String fldrImgsPath = _exePath+File.separator+"images";
String fldrImgsChampions = fldrImgsPath+File.separator+"champions";
File fldrImages = new File(fldrImgsPath);
if (fldrImages.isDirectory() || fldrImages.mkdir()){
File fldrChampions = new File(fldrImgsChampions);
if (fldrChampions.isDirectory() || fldrChampions.mkdir()){
JSONObject data = jsonChampions.getJSONObject("data");
JSONArray championsNames = data.names();
int _max = championsNames.length();
_status.setMaximum(_max);
if (_list == null)
_list = new ArrayList<LoLChampion>();
int curr = _list.size();
for (int i = 0; i < _max; i++){
_status.setString("Fetching ["+(curr+1)+"/"+_max+"] champions icos");
//Champion object
LoLChampion champion = new LoLChampion();
//Champion name
String name = String.valueOf(championsNames.get(i));
champion.setChampionName(name);
//Champion data
JSONObject jsonChamp = data.getJSONObject(name);
//Champion roles
JSONArray tags = jsonChamp.getJSONArray("tags");
//Main role
String mRole = String.valueOf(tags.get(0));
champion.setChampionMainRole(mRole);
//Secondary role (if exists)
String sRole = "";
if (tags.length() > 1)
sRole = String.valueOf(tags.get(1));
champion.setChampionSecondRole(sRole);
//Champion ico.
File pf = new File(fldrChampions.getPath()+File.separator+name+".jpg");
saveChampionImage(name, pf);
champion.setChampionIco(pf);
//Push LoLChampion object to list
_list.add(champion);
//Update status bar
curr = _list.size();
_status.setValue(curr);
System.gc();
}//for:i
_ddbb.setChampionsList(_list);
}else{
_log.error("Couldn't access or create \""+fldrImgsChampions+"\" folder");
throw new Exception("Couldn't access or create \""+fldrImgsChampions+"\" folder");
}//fi
}else{
_log.error("Couldn't access or create \""+fldrImgsPath+"\" folder");
throw new Exception("Couldn't access or create \""+fldrImgsPath+"\" folder");
}//fi
}
private void saveChampionImage(String name, File pf) throws Exception{
String endPointURL = (new ApiURLs()).getChampionsIcoURL();
endPointURL = endPointURL.replace("{version}", _version);
endPointURL = endPointURL.replace("{champion}", name);
try{
if (!pf.canWrite())
pf.createNewFile();
URL url = new URL(endPointURL);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(pf);
_log.info("Getting \""+endPointURL+"\"");
_log.info("Saving to \""+pf.getPath()+"\"");
byte[] buffer = new byte[2048];
int length;
while((length = is.read(buffer)) != -1){
os.write(buffer, 0, length);
}//while
is.close();
os.close();
}catch(Exception ex){
_log.error(ex.getMessage());
}
}
}
UPDATE
This is the complete JSON I want to parse:
https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?champData=tags&api_key=d34be821-7f22-4d55-85da-7409413e6379
I dont think your JSON example is well formed. JSON consists of name value pairs. There should be a ":" in between the name and a value.
Something like this:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
The JSON example you have provided looks malformed. Refer to json.org for more details

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.

Unit testing using MockMultipartHttpServletRequest (throws NullPointerException in ItemInputStream.makeAvailable)

I've written a transformer class that takes an HttpServletRequest and transforms it into another type that holds a pointer to the InputStream from the servlet request. (The idea is to abstract the incoming transport protocol from the request handling, so I could also write a similar transformer from FTP, for instance.)
Now I'm trying to write a unit test for this, and I'm having problems. I've managed to figure out the correct boilerplate to create a valid Multipart HTTP request (using the Spring classes MockMultipartHttpServletRequest and MockMultipartFile), but now I get a NullPointerException in the initialize() method of my UploadRequest class. I'm guessing the problem is that somehow the stream inside the MockMultipartHttpServletRequest isn't being initialized correctly, but I can't figure out what I should do differently.
Any suggestions would be gratefully accepted!
This is the stack trace:
java.lang.NullPointerException
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:976)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:886)
at java.io.InputStream.read(InputStream.java:82)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:96)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:66)
at org.apache.commons.fileupload.MultipartStream.readBodyData(MultipartStream.java:592)
at org.apache.commons.fileupload.MultipartStream.discardBodyData(MultipartStream.java:618)
at org.apache.commons.fileupload.MultipartStream.skipPreamble(MultipartStream.java:637)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:984)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:965)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.servlet.ServletFileUpload.getItemIterator(ServletFileUpload.java:148)
at com.ooyala.UploadRequest.initialize(UploadRequest.java:51)
at com.ooyala.UploadRequestTest.testCreateFromServletRequest(UploadRequestTest.java:57)
Here's an abbreviated version of my transformer class:
public class UploadRequest {
private Map<String, String> params;
private InputStream strIn;
private Logger Log = Logger.getLogger(UploadRequest.class.getName());
public UploadRequest()
{
params = new HashMap<String, String>();
}
public void initialize(HttpServletRequest sRequest,
ServletFileUpload upload)
throws IOException, FileUploadException
{
Enumeration<String> paramNames = sRequest.getParameterNames();
while (paramNames.hasMoreElements()) {
String pName = paramNames.nextElement();
params.put(pName, sRequest.getParameter(pName));
}
params.put("request_uri", sRequest.getRequestURI());
FileItemIterator iter = upload.getItemIterator(sRequest);
while (iter.hasNext()) {
FileItemStream item = iter.next();
try {
if (!item.isFormField()) {
// Skip form fields
params.put("original_file_name", item.getName());
strIn = item.openStream();
}
} catch (IOException ex) {
Log.severe("File uploading exception: " + ex.getMessage());
throw ex;
}
}
}
And here's the unit test:
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
// etc.... other imports
#RunWith(JMock.class)
public class UploadRequestTest {
private UploadRequest upRequest;
#Before
public void setUp()
{
context.setImposteriser(ClassImposteriser.INSTANCE);
upRequest = new UploadRequest();
}
#Test
public void testCreateFromServletRequest()
throws IOException, FileUploadException
{
String text_contents = "hello world";
MockMultipartHttpServletRequest sRequest =
new MockMultipartHttpServletRequest();
sRequest.setMethod("POST");
String boundary = generateBoundary();
String contentType = "multipart/form-data; boundary="+boundary;
sRequest.setContentType(contentType);
sRequest.setRequestURI("/foo");
sRequest.addParameter("test_param","test_value");
sRequest.addFile(
new MockMultipartFile("file1","test_upload.txt","text/plain",
text_contents.getBytes()));
ServletFileUpload upload = new ServletFileUpload();
assertTrue(upload.isMultipartContent(sRequest));
upRequest.initialize(sRequest, upload);
}
}
I have the same issue and I googled but no answer. I plugged in the source code from the library, You need to send content, whatever. The library might need to check if it is null in the skip method
MockMultipartHttpServletRequest request
request.setContent("whatever".getBytes());
Posted here for others
Add boundary condition
Generate contents as follows
MockMultipartHttpServletRequest request =
this.generateMockMultiPartHttpServletRequest(true);
MockMultipartFile mockMultipartFile = null;
try {
request.setContentType("multipart/form-data; boundary=-----1234");
request.setCharacterEncoding("text/plain");
String endline = "\r\n";
String bondary = "-----1234";
String textFile = this.encodeTextFile("-----1234", "\r\n", "file","test.csv",
"text/UTF-8", FileUtils.readFileToString((new File(csvFilePath)), "UTF-8"));
StringBuilder content = new StringBuilder(textFile.toString());
content.append(endline);
content.append(endline);
content.append(endline);
content.append("--");
content.append(bondary);
content.append("--");
content.append(endline);
request.setContent(content.toString().getBytes());
request.setMethod("POST");
mockMultipartFile = new MockMultipartFile("file",
FileUtils.readFileToByteArray(new File(csvFilePath)));
} catch (Exception e1) {
e1.printStackTrace();
}
request.addFile(mockMultipartFile);
Function to encode text
private String encodeTextFile(String bondary, String endline, String name,
String filename, String contentType, String content) {
final StringBuilder sb = new StringBuilder(64);
sb.append(endline);
sb.append("--");
sb.append(bondary);
sb.append(endline);
sb.append("Content-Disposition: form-data; name=\"");
sb.append(name);
sb.append("\"; filename=\"");
sb.append(filename);
sb.append("\"");
sb.append(endline);
sb.append("Content-Type: ");
sb.append(contentType);
sb.append(endline);
sb.append(endline);
sb.append(content);
return sb.toString();
}
I went through the same problem, after searching lot I got this post in which I answered with code that solved my problem.
The Shriprasad's solution works well for text file. But I had some problems with binary files.
https://stackoverflow.com/a/30541653/2762092

Categories

Resources