in xpages I can use:
var protocol = context.getUrl().getScheme() + "://";
var url:XSPUrl = new XSPUrl(database.getHttpURL());
var host = url.getHost();
...
to build urls to documents/files in documents
How should I build the URL's equivalent in Java?
I build URL's in Java all the time.
Here are some RANDOM code snippets that I use. This is not a single class, just random snippets that should help you get started at least.
FacesContext facesContext = FacesContext.getCurrentInstance();
XSPContext context = XSPContext.getXSPContext(facesContext);
String entryPage = context.getUrl().getPath() + context.getUrl().getQueryString();
if (entryPage.contains("/home.xsp")) {
this.console("Entry Page contains /home.xsp");
if (this.isBasicMode()) {
entryPage.replace("home.xsp", "basic_Menu.xsp");
}
} else {
this.console("entry page does NOT contain /home.xsp");
}
context.redirectToPage(“/myPage.xsp”);
public void redirectExternal(String url) throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExtenalContext externalContext = fc.getExternalContext();
externalContext.redirect(url);
}
public void redirectToPage(final String pageName) {
// pageName = "/myPage.xsp"
try {
// You'd think this would end all Java processing but that's NOT
// what happens
// It looks like the Java code will finish and only then will the
// redirection happen.
final String entryPage = JSFUtil.getXSPContext().getUrl().getPath() + JSFUtil.getXSPContext().getUrl().getQueryString();
FrameworkUtils.getSessionScope().put("entryPage", entryPage);
this.setEntryPage(entryPage);
JSFUtil.getXSPContext().redirectToPage(pageName);
} catch (final RedirectSignal rs) {
// Ignoring this error. Useless!
}
// Returning false so we can stop the calling code from continuing
// return false;
}
public String getParam(final String key) {
if (!this.getQueryString().containsKey(key)) {
return null;
} else {
return this.getQueryString().get(key);
}
}
#SuppressWarnings("unchecked")
public Map<String, String> getQueryString() {
final Map<String, String> qs = (Map<String, String>) FrameworkUtils.resolveVariable("param");
return qs;
}
depends where your documents files are. It think the best way is create a servlet in the nsf, call that by passing an docUNID and attachmentName. Then you can get the document and write the attachment as stream to the response. If you set the header to attachment, like
response.setHeader("Content-disposition", "attachment; filename=\""+attachment.getName()+"\"");
you will get the attachment as download
Related
I have implemented filter and I have called getEntityStream of ContainerRequestContext and set the exact value back by using setEntitystream. If i use this filter then #FormParameter data becomes null and if i don't use filter then everything will be fine (as I am not calling getEntityStream) and i have to use filter to capture request data.
Note: I am getting form params from MultivaluedMap formParams but not from #FormParameter.
Environment :- Rest Easy API with Jboss Wildfly 8 server.
#Provider
#Priority(Priorities.LOGGING)
public class CustomLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter{
final static Logger log = Logger.getLogger(CustomLoggingFilter.class);
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
MDC.put("start-time", String.valueOf(System.currentTimeMillis()));
String entityParameter = readEntityStream(requestContext);
log.info("Entity Parameter :"+entityParameter);
}
private String readEntityStream(ContainerRequestContext requestContext){
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
final InputStream inputStream = requestContext.getEntityStream();
final StringBuilder builder = new StringBuilder();
int read=0;
final byte[] data = new byte[4096];
try {
while ((read = inputStream.read(data)) != -1) {
outStream.write(data, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] requestEntity = outStream.toByteArray();
if (requestEntity.length == 0) {
builder.append("");
} else {
builder.append(new String(requestEntity));
}
requestContext.setEntityStream(new ByteArrayInputStream(requestEntity) );
return builder.toString();
}
return null;
}
}
class customResource
{
//// This code is not working
#POST
#Path("voiceCallBack")
#ApiOperation(value = "Voice call back from Twilio")
public void voiceCallback(#FormParam("param") String param)
{
log.info("param:" + param);
}
// This code is working
#POST
#Path("voiceCallBackMap")
#ApiOperation(value = "Voice call back from Twilio")
public void voiceCallbackMap(final MultivaluedMap<String, String> formParams)
{
String param = formParams.getFirst("param");
}
}
please suggest me solution & Thanks in Advance.
I found during run time that instance of the entity stream (from http request) is of type org.apache.catalina.connector.CoyoteInputStream (I am using jboss-as-7.1.1.Final). But we are setting entity stream with the instance of java.io.ByteArrayInputStream. So Resteasy is unable to bind individual formparmeters.
There are two solutions for this you can use any one of them :
Use this approach How to read JBoss Resteasy's servlet request twice while maintaing #FormParam binding?
Get form parameters like this:
#POST
#Path("voiceCallBackMap")
#ApiOperation(value = "Voice call back from Twilio")
public void voiceCallbackMap(final MultivaluedMap<String, String> formParams)
{
String param = formParams.getFirst("param");
}
I have a requirement where I need to get the page name from the request in the doView method and redirect it to page_name_SUFIX but I can't find a way to decode the WebSphere URL
When I request the view for 'pageName' I have to do something like this:
public void doView(RenderRequest req, RenderResponse res) {
String decodedURL = decodeURL(req); // This is the method that I need, decodedURL should be 'pageName'
(...)
}
I am working on WebSphere 8.0 and I've tried the following without results.
http://wpcertification.blogspot.com.ar/2010/05/getting-name-of-page-where-your-portlet.html (Here i've got the page title, but i don't know how to get the name)
WebSphere Portal decode url (I've decoded the URL but I can't find the page name in the XML)
There's some way to achieve this?
Thank you in advance!
So the question is of scope, from above it is unclear if you mean pageName as in the uniqueName of the page? If so once you have the objectid in a string or the actual object you can get the uniqueName from that object.
here is code to get the objectId of the current page
public ObjectID getCurrentPage(PortletRequest request,
PortletResponse response) throws StateException, NamingException,
IOException {
ObjectID oId = null;
try {
NavigationSelectionModelProvider provider = getNavigationSelectionModelProvider();
NavigationSelectionModel model = provider
.getNavigationSelectionModel(request, response);
NavigationNode node = (NavigationNode) model.getSelectedNode();
oId = node.getObjectID();
} catch (ModelException e) {
System.err.println("The current page could not be located = " + e);
}
return oId;
}
Now if your question is about a portlet parameter called pageName then it should be in the decoded url. is it the uniqueName you are looking for? that will not be in the xml but you can get that from the objectid object
you should be able to get the page id/uniqueName by using a doView method similar to this:
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());
PortletServiceHome nsh = null;
javax.naming.Context ctx;
boolean serviceAvailable = false;
try {
ctx = new javax.naming.InitialContext();
nsh = (PortletServiceHome)ctx.lookup("portletservice/com.ibm.portal.portlet.service.model.NavigationSelectionModelProvider");
serviceAvailable = true;
} catch(NameNotFoundException nnfe) {
nnfe.printStackTrace();
} catch(NamingException ne) {
ne.printStackTrace();
}
// Check if portlet session exists
ShowPageLayoutPortletSessionBean sessionBean = getSessionBean(request);
if( sessionBean==null ) {
response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
return;
} else if(!serviceAvailable) {
response.getWriter().println("<b>NO SERVICE AVAILABLE</b>");
return;
}
try {
NavigationSelectionModelProvider nsProvider = (NavigationSelectionModelProvider) nsh.getPortletService(NavigationSelectionModelProvider.class);
NavigationSelectionModel navmodel = nsProvider.getNavigationSelectionModel(request, response);
NavigationNode navNode = (NavigationNode)navmodel.getSelectedNode();
ContentPage contentPage = (ContentPage)navNode.getContentNode();
ObjectID pageId = contentPage.getObjectID();
// Invoke the JSP to render
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
rd.include(request,response);
} catch(Exception ex) {
ex.printStackTrace();
}
}
We have one screen/page in our application where we are showing different columns for different products. These all records in the columns are fetched from database.
Also, We have two export buttons at the bottom of the screen which is meant for showing all those records in the PDF and XLS format.
These functionalities are working fine except under one condition. We have one column name in the screen whose values are fetched from database. when any record under name column has & in it, the export functionality stopped working.
For example :-
for name "BOWOG BEHEER B.V.", the export is working fine for both pdf and xls.
But for the name "BOWOG & BEHEER B.V.", it stopped working. While clicking on export button, pdf and xls is showing as blank page.
Could anyone please help ?
Below is the piece of codes :- (not full code)
public class CVRExportServlet extends HttpServlet {
private final SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
/** context. */
private ResourceContext context = null;
private Map createParametersFromRequest(final HttpServletRequest request) {
// copy all request parameters
final Map parameters = new HashMap();
final Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
final String name = (String) names.nextElement();
final String[] values = request.getParameterValues(name);
if (values.length > 1) {
parameters.put(name, values);
} else {
parameters.put(name, values[0]);
}
}
// parse request uri to get type and format
final String requestURI = request.getRequestURI();
String type = StringUtils.left(requestURI, requestURI.lastIndexOf('.'));
type = StringUtils.substring(type, requestURI.lastIndexOf('/') + 1);
final String format = StringUtils.substring(requestURI, requestURI.lastIndexOf('.') + 1);
parameters.put(Constants.EXPORT_TYPE_PARAMETER, type);
parameters.put(Constants.EXPORT_FORMAT_PARAMETER, format);
// determine themeUrl
final String requestUrl = request.getRequestURL().toString();
final int index = requestUrl.indexOf(request.getContextPath());
String server = "";
if (index > -1) {
server = requestUrl.substring(0, index);
}
private void fillParameters(final HttpServletRequest request, final HttpServletResponse response, final Map parameters)
throws ApplicationException {
parameters.put("props", ResourceBundle.getBundle("messages"));
// Create search request using the search form
final SearchForm form = (SearchForm) request.getSession().getAttribute(
(String) request.getSession().getAttribute(CvrConstants.SESS_ATTR_CVR_SEARCH_FORM_NAME));
final SearchRequest searchRequest = form.getSearchRequest();
searchRequest.setPageNumber(1);
searchRequest.setRowsPerPage(10000);
parameters.put("searchRequest", searchRequest);
}
public void service(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
final long startTime = System.currentTimeMillis();
// create parameters from request
final Map parameters = this.createParametersFromRequest(request);
parameters.put(ResourceContext.class.getName(), this.context);
try {
this.fillParameters(request, response, parameters);
final SearchRequest searchRequest = (SearchRequest) parameters.get("searchRequest");
if (searchRequest == null || searchRequest.getCounterPartyList() == null
|| searchRequest.getCounterPartyList().isEmpty()) {
throw new ExportException("Exception occurred while handling export: empty counterparty list");
} else {
if (searchRequest.getCounterPartyList().size() == 1) {
this.handleSingleReportExport(response, parameters);
} else {
this.handleMutlipleReportExport(response, parameters);
}
}
} catch (final Exception e) {
this.handleException(e, request, response);
}
}
private void handleSingleReportExport(final HttpServletResponse response, final Map parameters) throws Exception {
final XmlExportService exportService = this.getXmlExportService();
final ApplicationContext context = this.getApplicationContext();
final XmlTransformationService xmlTransformationService = (XmlTransformationService) context.getBean("transformationService");
// perform export
exportService.export(parameters);
// perform transformation
final ExportResult exportResult = xmlTransformationService.transform(parameters);
// write result to stream
response.setContentType(exportResult.getContentType());
response.setContentLength(exportResult.getContentLength());
if (parameters.get("format").equals("csv")) {
response.setContentType("text/csv");
response.setHeader("Content-disposition", "attachment; filename=export.csv");
} else if (parameters.get("format").equals("pdf")) {
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=export.pdf");
}
final ServletOutputStream out = response.getOutputStream();
out.write(exportResult.getBytes());
out.flush();
out.close();
}
private void handleMutlipleReportExport(final HttpServletResponse response, final Map parameters) throws Exception {
final SearchRequest searchRequest = (SearchRequest) parameters.get("searchRequest");
response.setContentType("application/force-download");
response.setHeader("Content-Encoding" , "x-compress");
response.setHeader("Content-Disposition", "attachment; filename=export_" + parameters.get("format") + ".zip");
final XmlExportService exportService = this.getXmlExportService();
final ApplicationContext context = this.getApplicationContext();
final XmlTransformationService xmlTransformationService = (XmlTransformationService) context.getBean("transformationService");
// start the zip process
final ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
// create a file for each counterparty and add it to the zip file
for (final String counterPartyId : searchRequest.getCounterPartyList()) {
// make sure to reset the counterparty to the current one in the loop
searchRequest.setCounterPartyList(Arrays.asList(new String[] {counterPartyId}));
// perform export
exportService.export(parameters);
// perform transformation
final ExportResult exportResult = xmlTransformationService.transform(parameters);
// add the file to the zip
final String fileName = counterPartyId + "_" + sdf.format(searchRequest.getRevaluationDate()) + "." + parameters.get("format");
zos.putNextEntry(new ZipEntry(fileName));
zos.write(exportResult.getBytes());
zos.closeEntry();
}
// finish the zip process
zos.flush();
zos.close();
}
I have some idea now. actually the issue is there at vm (velocity template). The "name" column is fetched from vm file and code is something like this :-
$!{result.counterpartyName}
This is in for each loop for multiple records. Could anyone please suggest how can i ignore special characters in the vm file itself. so that we will be able to export correctly even if "name" column has "&" or "-" etc special characters.
It seems based on your code that you are using an XML transformation service.
I'd say it's probably your data in your parameters containing dangling & sign. To be valid XML ready for transformation, & should be &. However, based on the code given it is not possible to say where the XML data is coming from. You say it's coming from the database, so my guess is that the problem should be dealt with by modifying the data in the database.
Edit:
It seems I was partly right, but the database doesn't contain the XML - if I got this correctly, data is coming from database as raw tabular data, but is formatted to XML using velocity templates. If that's it, then XML escaping should be used in velocity template like this.
I am working on below scenario since last two days,
I have developed a java filter that check whether request is multipart type,
If it is, I want to restrict .php file getting uploaded.
In servlet filter I successfully retrieved type of file, if it's valid one, i have forwarded that request to proceed.
Now my business logic that was working exactly fine without filter is now failed to upload.
My project is using Spring framework.
At business logic, I'm using MultipartRequest(class of spring) as casting in.
Invoking request.getFileNames() which is returning nothing after involving filter.
In filter, I have wrapped request after validating file extensions as follows:
All form fields are set in parameter map that will be passed with request.
And File type field is set as attribute in request object.
Would you guys please help?
Thanks,
Namrata Shah
In doFilter(),
I have checked whether received request is instance of HttpServletRequest. If yes, then it'll be parsed if it's a multipart req using below code:
parseRequest():
{
List<FileItem> multipartItems = null;
try
{ multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
}
catch (FileUploadException e)
{
throw new ServletException("Cannot parse multipart request: " + e.getMessage());
}
Map<String, String[]> parameterMap = new HashMap<String, String[]>();
for (FileItem multipartItem : multipartItems)
{
if (multipartItem.isFormField())
processFormField(multipartItem, parameterMap);
else
processFileField(multipartItem, request);
}
return wrapRequest(request, parameterMap);
}
Code for processFileField():
request.setAttribute(fileField.getFieldName(), fileField);
then, I wrap request as follows:
private static HttpServletRequest wrapRequest(
HttpServletRequest request, final Map<String, String[]> parameterMap)
{
return new HttpServletRequestWrapper(request)
{
#Override
public Map<String, String[]> getParameterMap()
{
return parameterMap;
}
public String[] getParameterValues(String name)
{
return parameterMap.get(name);
}
public String getParameter(String name)
{
String[] params = getParameterValues(name);
return params != null && params.length > 0 ? params[0] : null;
}
public Enumeration<String> getParameterNames()
{
return Collections.enumeration(parameterMap.keySet());
}
};
}
Code for processFormField():
String name = formField.getFieldName(),value = formField.getString();
String[] values = parameterMap.get(name);
if (values == null)
{
parameterMap.put(name, new String[]{value});
}
else
{
int length = values.length;
String[] newValues = new String[length + 1];
System.arraycopy(values, 0, newValues, 0, length);
newValues[length] = value;
parameterMap.put(name, newValues);
}
I am following this tutorial on uploading files to a server from android, but I cannot seem to get the code right on the server side. Can somebody please help me code the Web Api post method that would work with that android java uploader? My current web api controller class looks like this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WSISWebService.Controllers
{
public class FilesController : ApiController
{
// GET api/files
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/files/5
public string Get(int id)
{
return "value";
}
// POST api/files
public string Post([FromBody]string value)
{
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
Stream requestStream = task.Result;
try
{
Stream fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + value));
requestStream.CopyTo(fileStream);
fileStream.Close();
requestStream.Close();
}
catch (IOException)
{
// throw new HttpResponseException("A generic error occured. Please try again later.", HttpStatusCode.InternalServerError);
}
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response.ToString();
}
// PUT api/files/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/files/5
public void Delete(int id)
{
}
}
}
I am pretty desperate to get this working as the deadline is tuesday. If anybody could help that would be much appreciated.
you can post a files as multipart/form-data
// POST api/files
public async Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
string value;
try
{
// Read the form data and return an async data.
var result = await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
// return multiple value from FormData
if (key == "value")
value = val;
}
}
if (result.FileData.Any())
{
// This illustrates how to get the file names for uploaded files.
foreach (var file in result.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
if (fileInfo.Exists)
{
//do somthing with file
}
}
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id }));
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}