How would I receive all fields from a dynamic form with Struts? - forms

I found myself with the following problem:
I have a page generated with logic:iterate that shows the current supervisor and assistant of a service.
That page also acts as a form where people can add their possible substitutes, but you never know how many of those are there.
Due to the environment I am currently working with it had to be without JSTL so a lot of options were gone; couldn't get DynaActionForm working for this either.

Since I couldn't find anything but I already got the answer I decided to create this to answer anyone who might have the same issue.
Code:
public ActionForward post(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String[] tot;
try {
Enumeration<?> fieldsForm = request.getParameterNames();
while(fieldsForm.hasMoreElements()) {
String current = (String) fieldsForm.nextElement();
tot = request.getParameterValues(current);
System.out.println("Field name is: " + current);
for (i=0; i<tot.length; i++) {
// do whatever you need to do; contents are in tot[i]
System.out.println("Value " + i + " is: " + tot[i]);
}
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}

Related

Domino REST Service - Can't get parameter from GET Call

I can't seem to get json handed into a GET call in the serviceBean.
<xe:restService id="restService1" pathInfo="getaccount">
<xe:this.service>
<xe:customRestService requestContentType="application/json" serviceBean="web.service.GetAccount" contentType="application/json"/>
</xe:this.service>
</xe:restService>
For the pathInfo I've tried pathInfo="getaccount", pathInfo="getaccount/{id}", pathInfo="getaccount{id}"
The serviceBean:
public class GetAccount extends CustomServiceBean {
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
XspOpenLogUtil.logEvent(null, "getAccount()", Level.INFO, null);
Map parameters = engine.getHttpRequest().getParameterMap();
XspOpenLogUtil.logEvent(null, "getAccount() - getHttpRequest().getParameterMap(): " + parameters.toString(), Level.INFO, null);
String json_string = IOUtils.toString(engine.getHttpRequest().getInputStream(), "UTF-8");
XspOpenLogUtil.logEvent(null, "getAccount() - jsonReaderString: " + json_string, Level.INFO, null); }
I can get the json_string if I change to a POST, but I should be able to perform a GET and send some json in i.e. { "id": "1234" }
Using SoapUI with the resource as api.xsp/getaccount{id} and a parameter Name=id and Value=1234
Thanks,
Scott.
I figured it out. You can use the engine.getHttpRequest().getRequestURI(), which will give you the URI handed in e.g. api.nsf/api.xsp/getaccount/Bob.Smith%40mail.com. Run a URLDecode to cleanup the encoding.
Hope this helps others trying to sort this out.
Scott.

Exception in httpunit

I am having a HttpUnit code,in which I am trying to access google''s official website.Here is my code:
/** everything you need to start is in the com.meterware.httpunit package **/
import com.meterware.httpunit.*;
/** This is a simple example of using HttpUnit to read and understand web pages. **/
public class Example {
public static void main(String[] params) {
try {
WebConversation wc = new WebConversation();
String url = "https://www.yahoo.com";
WebRequest request = new GetMethodWebRequest(url);
WebResponse response = wc.getResponse(request);
// WebLink httpunitLink = response.getFirstMatchingLink(
// WebLink.MATCH_CONTAINED_TEXT, "HTML" );
// response = httpunitLink.click();
System.out.println("The yahoo main page '" + url + "' contains "
+ response.getLinks().length + " links");
} catch (Exception e) {
System.err.println("Exception: " + e);
}
}
}
I am getting the below exception on running the code.I am using eclipse as IDE.
org.mozilla.javascript.EcmaError: TypeError: Cannot read property "className" from undefined (httpunit#3)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3229)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3219)
at org.mozilla.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3235)
at org.mozilla.javascript.ScriptRuntime.typeError2(ScriptRuntime.java:3254)
at org.mozilla.javascript.ScriptRuntime.undefReadError(ScriptRuntime.java:3267)
at org.mozilla.javascript.ScriptRuntime.getObjectProp(ScriptRuntime.java:1324)
at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:2816)
at script(httpunit:3)
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:2251)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:161)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:340)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:2758)
at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:172)
at org.mozilla.javascript.Context.evaluateString(Context.java:1132)
at com.meterware.httpunit.javascript.ScriptingEngineImpl.runScript(ScriptingEngineImpl.java:92)
at com.meterware.httpunit.scripting.ScriptableDelegate.runScript(ScriptableDelegate.java:88)
at com.meterware.httpunit.parsing.NekoDOMParser.runScript(NekoDOMParser.java:151)
at com.meterware.httpunit.parsing.ScriptFilter.getTranslatedScript(ScriptFilter.java:150)
at com.meterware.httpunit.parsing.ScriptFilter.endElement(ScriptFilter.java:131)
at org.cyberneko.html.filters.DefaultFilter.endElement(DefaultFilter.java:249)
at org.cyberneko.html.filters.NamespaceBinder.endElement(NamespaceBinder.java:367)
at org.cyberneko.html.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1015)
at org.cyberneko.html.HTMLTagBalancer.endElement(HTMLTagBalancer.java:888)
at org.cyberneko.html.HTMLScanner$SpecialScanner.scan(HTMLScanner.java:2831)
at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:809)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:478)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:431)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at com.meterware.httpunit.parsing.NekoHTMLParser.parse(NekoHTMLParser.java:48)
at com.meterware.httpunit.HTMLPage.parse(HTMLPage.java:271)
at com.meterware.httpunit.WebResponse.getReceivedPage(WebResponse.java:1301)
at com.meterware.httpunit.WebResponse.getFrames(WebResponse.java:1285)
at com.meterware.httpunit.WebResponse.getFrameRequests(WebResponse.java:1024)
at com.meterware.httpunit.FrameHolder.updateFrames(FrameHolder.java:179)
at com.meterware.httpunit.WebWindow.updateFrameContents(WebWindow.java:315)
at com.meterware.httpunit.WebClient.updateFrameContents(WebClient.java:526)
at com.meterware.httpunit.WebWindow.updateWindow(WebWindow.java:201)
at com.meterware.httpunit.WebWindow.getSubframeResponse(WebWindow.java:183)
at com.meterware.httpunit.WebWindow.getResponse(WebWindow.java:158)
at com.meterware.httpunit.WebClient.getResponse(WebClient.java:122)
at Example.main(Example.java:14)
Exception: com.meterware.httpunit.ScriptException: Script '//used for perf beacons in 3pas
rtTop = Number(new Date());
document.documentElement.className += ' jsenabled';
if (!("ontouchstart" in document.documentElement)) {
document.documentElement.className += " no-touch";
}
(function(){var k=13,d=4,j=0,a=document.documentElement,b=[a.className],f,c=navigator.plugins,g=k;if(c&&c.length){f=c["Shockwave Flash"];if(f&&f.description){j=parseInt(f.description.match(/\b(\d+)\.\d+\b/)[1],10)||0}}else{while(g--){try{new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+g);j=g;break}catch(h){}}}b.push("flash-"+j);while(j-->d){b.push("flash-gt"+j)}a.className=b.join(" ")})();
(function(){var j=this,n=/^(on)?load/,b=/^on/,i="addEventListener",f="attachEvent",e="_oc",h="detachEvent",g="removeEventListener",l=j[i],m=j[g],p=j[f],a=j[h],k={},d=0;function c(r,s,q){if(!r||!s){return;}if(n.test(r)){if(!s[e]){var t=++d;s[e]=t;k[t]=s;}}else{if(p&&b.test(r)){p(r,s);}else{if(l){l(r,s,q);}}}}function o(r,s,q){if(!r||!s){return;}if(n.test(r)){var t=s[e];if(t){delete k[t];}}else{if(a&&b.test(r)){a(r,s);}else{if(m){m(r,s,q);}}}}j.OnloadCache={enable:function(){if(l){j[i]=c;j[g]=o;}if(p){j[f]=c;j[h]=o;}},disable:function(){if(l){j[i]=l;j[g]=m;}if(p){j[f]=p;j[h]=a;}},dispatch:function(){var r={type:"load"},q;for(q in k){if(k.hasOwnProperty(q)){k[q](r);}}},reset:function(){k={};}};})();
OnloadCache.enable();
var setJSCookie = true;
(function () {
var cookieName = "FBJSC=";
var cookieValue = "1409123746";
var cookieIndex = document.cookie.indexOf(cookieName);
if(cookieIndex >= 0) {
var oldValue = document.cookie.substr(cookieIndex + cookieName.length, cookieValue.length);
if(cookieValue <= oldValue) {
setJSCookie = false;
}
}
if(setJSCookie) {
document.cookie = cookieName + cookieValue;
}
})();' failed: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "className" from undefined (httpunit#3)
Any help would be greatly appreciated.Thanks.enter code here
As one of the httpunit committers I'd recommend reading the FAQ:
http://httpunit.sourceforge.net/doc/faq.html
JavaScript support of httpunit is limited. The Error you are getting is showing that you ran into JavaScript code that is more complicated than what httpunit can handle. As a work-around you might want to switch off javascript altogether (if that is possible in your use case).
The following is from HttpUnit's developer FAQ:
HttpUnit 1.x support of Javascript is limited. There is a new Javascript engine in development but the development is almost stalled due to limited resources.
To work around the issue you might want to
try the new scripting engine
switch off javascript
if you get an org.mozilla.javascript.EcmAError ... undefined ... find the missing javascript function, implement it and supply the patch for the community see "6. How can I suggest modifications to httpunit?"

Quickbooks API V2 QBD - Looking for example of how to use RecordCountQuery

I am working in .NET, using the QuickBooks V2 API to try and fetch a count of the number of Items the user's QBD.
Does anyone have a working example of how to implement the "RecordCountQuery" class to find the # of Items in QBD?
Here is one of my attempt to do so:
//
// Get a record count of the items
//
var qbItemsCount = new RecordCountQuery();
var myResults = qbItemsCount.ExecuteQuery<Item>(_oQBIDataServices.ServiceContext);
Error:
Intuit.Ipp.Exception.IdsException was unhandled by user code
HResult=-2146233088
Message= The RecordCountQuery xml must wrap an existing supported query object. Please modify your query and try again.
Source=""
ErrorCode=-2015
I gather by this that I should be using an different type in the "ExecuteQuery" method like Intuit.Ipp.Data.QBD.ItemQuery. I tried this but got a different error.
So what I am asking for is not necessarily correction to the above code, but a WORKING EXAMPLE of the RecordCountQuery class in .NET.
Thank you.
Edit - Adding .net code
RecordCountQuery query = new RecordCountQuery();
CustomerQuery custQuery = new CustomerQuery();
query.Item1 = custQuery;
List<RecordCount> customerRecordCountQuery = query.ExecuteQuery<RecordCount>(context).ToList();
string customerCount = customerRecordCountQuery[0].Count;
I hv a working java code. Please check if it is useful.
API endpoint - https://services.intuit.com/sb/recordcount/v2/{*relam_id*}
POST body
<RecordCountQuery xmlns="http://www.intuit.com/sb/cdm/v2">
<CustomerQuery/>
</RecordCountQuery>
Response
<?xml version="1.0" encoding="UTF-8"?><!--XML GENERATED by IntuitDataSyncEngine (IDS) using \\SBDomainServices\CDM\branches\3.9.0-rel-1-->
<RestResponse xmlns="http://www.intuit.com/sb/cdm/v2"
xmlns:xdb ="http://xmlns.oracle.com/xdb"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://www.intuit.com/sb/cdm/v2 ../common/RestDataFilter.xsd"><RecordCounts>
<RecordCount>
<ObjectName>Customer</ObjectName>
<Count>392</Count>
</RecordCount>
</RecordCounts></RestResponse>
Java Code
public int testGetCount() {
int objectCount = 0;
try {
QBCustomerQuery CustomerQuery = QBObjectFactory.getQBObject(
context, QBCustomerQuery.class);
QBDRecordCountService iRecordCountSer = QBDServiceFactory
.getService(context, QBDRecordCountService.class);
List<QBRecordCountImpl> recordCounts = iRecordCountSer.getCount(
context, CustomerQuery);
Iterator<QBRecordCountImpl> iterator = recordCounts.iterator();
while (iterator.hasNext()) {
QBRecordCountImpl next = iterator.next();
objectCount = Integer.parseInt(next.getCount().toString());
}
System.out.println("Customer count - " + objectCount);
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return objectCount;
}
Thanks

Update records using Salesforce REST API - Patch method not working

I'm trying to update a record residing in salesforce table. Im using the Java HttpClient REST API to do the same. Getting an error when we use PATCH to update a record in Salesforce.
PostMethod post = new PostMethod(
instanceUrl + "/services/data/v20.0/sobjects/" +
objectName + "/" + Id + "?_HttpMethod=PATCH"
);
[{"message":"HTTP Method 'PATCH' not allowed. Allowed are HEAD,GET,POST","errorCode":"METHOD_NOT_ALLOWED"}]
Also tried doing the following:
PostMethod post = new PostMethod(
instanceUrl + "/services/data/v20.0/sobjects/" + objectName + "/" + Id)
{
public String getName() { return "PATCH";
}
};
This also returns the same error. We are using apache tomcat with commons-httpclient-3.1.jar library. Please advise on how this can be done.
Please check if you you're using the right implementation of PATCH method, see: Insert or Update (Upsert) a Record Using an External ID.
Also check if your REST URL is correct, probably your objectId is not passed in correctly from Javascript.
The ObjectName is the Name of an Salesforce table i.e. 'Contact'. And Id is the Id of a specific record you want to update in the table.
Similar:
Can I update without an ID?
for Drupal: How to deal with SalesforceException: HTTP Method 'PATCH' not allowed. Allowed are HEAD,GET,POST
As I think you're aware, commons httpclient 3.1 does not have the PATCH method, and the library has been end-of-lifed. In your code above, you're trying to add the HTTP method as a query parameter, which doesn't really make sense.
As seen on SalesForce Developer Board, you can do something like this instead:
HttpClient httpclient = new HttpClient();
PostMethod patch = new PostMethod(url) {
#Override
public String getName() {
return "PATCH";
}
};
ObjectMapper mapper = new ObjectMapper();
StringRequestEntity sre = new StringRequestEntity(mapper.writeValueAsString(data), "application/json", "UTF-8");
patch.setRequestEntity(sre);
httpclient.executeMethod(patch);
This allows you to PATCH without switching out your httpclient library.
I created this method to send the patch request via the Java HttpClient class.
I am using JDK V.13
private static VarHandle Modifiers; // This method and var handler are for patch method
private static void allowMethods(){
// This is the setup for patch method
System.out.println("Ignore following warnings, they showed up cause we are changing some basic variables.");
try {
var lookUp = MethodHandles.privateLookupIn(Field.class, MethodHandles.lookup());
Modifiers = lookUp.findVarHandle(Field.class, "modifiers", int.class);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
try {
Field methodField = HttpURLConnection.class.getDeclaredField("methods");
methodField.setAccessible(true);
int mods = methodField.getModifiers();
if (Modifier.isFinal(mods)) {
Modifiers.set(methodField, mods & ~Modifier.FINAL);
}
String[] oldMethods = (String[])methodField.get(null);
Set<String> methodsSet = new LinkedHashSet<String>(Arrays.asList(oldMethods));
methodsSet.addAll(Collections.singletonList("PATCH"));
String[] newMethods = methodsSet.toArray(new String[0]);
methodField.set(null, newMethods);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}

GWT Upload/Download best practices

So I am new to GWT and am not sure what the best programming practices are for what I am trying to do. In my web application the user will be able to upload a data file, my application needs to be able to access this file, do some stuff to it, and then let the user download the manipulated file.
So far I have been able to successfully upload a file with an upload servlet with this doPost method:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
fileUpload.setSizeMax(FILE_SIZE_LIMIT);
List<FileItem> items = fileUpload.parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
logger.log(Level.INFO, "Received form field:");
logger.log(Level.INFO, "Name: " + item.getFieldName());
logger.log(Level.INFO, "Value: " + item.getString());
} else {
logger.log(Level.INFO, "Received file:");
logger.log(Level.INFO, "Name: " + item.getName());
logger.log(Level.INFO, "Size: " + item.getSize());
}
if (!item.isFormField()) {
if (item.getSize() > FILE_SIZE_LIMIT) {
resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File size exceeds limit");
return;
}
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
fileName = getServletContext().getRealPath("/uploadedFiles/" + fileName);
byte[] data = item.get();
FileOutputStream fileOutSt = new FileOutputStream(fileName);
fileOutSt.write(data);
fileOutSt.close();
if (!item.isInMemory())
item.delete();
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
throw new ServletException(e);
}
}
When I look in my war folder, the uploadedFiles folder is created successfully and files are put there.
At this point I am a bit stuck, I have been researching but cannot seem to find a clear concise answer on what is the best way for me to access the uploaded files on the client side in order to manipulate them and then allow the user to download them. Maybe I am approaching this wrong, I am not sure. If someone could point me in the right direction or show me some good examples of the right way to do things that would be great, thanks.
To access the file in client side you need a new servlet or the same you are using with a doGet method.
The client should ask for the file via an Anchor or an Image depending on the file type but adding a parameter so as the server is able to identify the file. Normally you can use the name of the FileInput you used for uploading or maybe you could return a tag from the server.
I would recommend to you to take a try to gwt-upload, it would save a lot of time to you.
I solved my problem. When the file was successfully uploaded, I stored the file name. Later I used a RPC to access the file on the server. I passed the file name to the RPC so that it knows what file I am working on, then it looks for that file in the upload folder. So I can create the java file like this,
File file = new File((this.getServletContext().getRealPath("uploadedFiles") + File.separator + fileName));
and manipulate it how I see fit.