Help with using getLastChild() method with DOM
Hello all,
I have a XML doc that looks like this:
<?xml version="1.0"?>
<conf_rooms>
<conf_room>
<conf_id>8200</conf_id>
<conf_name>Conf 1</conf_name>
</conf_room>
<conf_room>
<conf_id>8201</conf_id>
<conf_name>Conf 2</conf_name>
</conf_room>
<conf_room>
<conf_id>8202</conf_id>
<conf_name>Conf 3</conf_name>
</conf_room>
<conf_room>
<conf_id>8203</conf_id>
<conf_name>Conf 4</conf_name>
</conf_room>
<conf_room>
<conf_id>8204</conf_id>
<conf_name>Conf 5</conf_name>
</conf_room>
<conf_room>
<conf_id>8205</conf_id>
<conf_name>Conf 6</conf_name>
</conf_room>
<conf_room>
<conf_id>8206</conf_id>
<conf_name>Conf 7</conf_name>
</conf_room>
<conf_room>
<conf_id>8207</conf_id>
<conf_name>sdfsdf</conf_name>
</conf_room>
<conf_room>
<conf_id>8208</conf_id>
<conf_name>Conf 9</conf_name>
</conf_room>
<conf_room>
<conf_id>8209</conf_id>
<conf_name>Conf 10</conf_name>
</conf_room>
</conf_rooms>In my code I need to get the value of the <conf_name> element.
Here is my code that successfully returns the <conf_id> element:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setCoalescing(true);
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(file);
NodeList confrooms = document.getElementsByTagName("conf_room");
int is = confrooms.getLength();
for(int i=0;i<is;i++)
Element confroom = (Element) confrooms.item(i);
Node title = confroom.getFirstChild();
while(title != null && title.getNodeType() != Node.ELEMENT_NODE)
title = title.getNextSibling();
if(title != null)
System.out.println(title.getFirstChild().getNodeValue());
}Now since my xml doc only has a <conf_id> and a <conf_name> I thought that if I replaced the following :
Node title = confroom.getFirstChild();
with
Node title = confroom.getLastChild();
it would return the value of <conf_name>
Doesnt work, doesnt return any value.
Any ideas or help would be greatly appreciated!!!
TIA!
Dr.Clap is right. You have to watch out for that. Here is what one of your conf_room nodes looks like:
NODE:
NAME: conf_room
TYPE: element
VALUE: null
CHILDREN:
NODE:
NAME: #text
TYPE: text
VALUE:
NODE:
NAME: conf_id
TYPE: element
VALUE: null
CHILDREN:
NODE:
NAME: #text
TYPE: text
VALUE: 8209
NODE:
NAME: #text
TYPE: text
VALUE:
NODE:
NAME: conf_name
TYPE: element
VALUE: null
CHILDREN:
NODE:
NAME: #text
TYPE: text
VALUE: Conf 10
NODE:
NAME: #text
TYPE: text
VALUE:As you can see, the whitespace is in there as text nodes. When you replace getFirstChild with getLast child you get a reference to that last empty text node. Then, your while loop executed and tried to move to the next sibling, which is null.
You could change your for loop to something like:
for(int i=0;i<is;i++)
Element confroom = (Element) confrooms.item(i);
System.out.println("CONF ID: " + confroom.getElementsByTagName("conf_id").item(0).getTextContent());
System.out.println("CONF NAME: " + confroom.getElementsByTagName("conf_name").item(0).getTextContent());
}The other option would be to create a simple Schema for your XML. That way you can set factory.setIgnoringElementContentWhitespace() which will eliminate all those extra whitespace nodes (and insure your XML is valid).
-Paco
Similar Messages
-
I would love some help with this issue. I have configured my SharePoint foundation 2010 site to use Claims Based Auth with Certificate authentication method with ADFS 2.0 I have a test account set up with lab.acme.com to use the ACS.
When I log into my site using Windows Auth, everything is great. However when I log in and select my ACS token issuer, I get sent, to the logon page of the ADFS, after selected the ADFS method. My browser prompt me which Certificate identity I want
to use to log in and after 3-5 second
and return me the logon page with error message “Authentication failed”
I base my setup on the technet article
http://blogs.technet.com/b/speschka/archive/2010/07/30/configuring-sharepoint-2010-and-adfs-v2-end-to-end.aspx
I validated than all my certificate are valid and able to retrieve the crl
I got in eventlog id 300
The Federation Service failed to issue a token as a result of an error during processing of the WS-Trust request.
Request type: http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue
Additional Data
Exception details:
Microsoft.IdentityModel.SecurityTokenService.FailedAuthenticationException: MSIS3019: Authentication failed. ---> System.IdentityModel.Tokens.SecurityTokenValidationException:
ID4070: The X.509 certificate 'CN=Me, OU=People, O=Acme., C=COM' chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. 'A certification chain processed
correctly, but one of the CA certificates is not trusted by the policy provider.
at Microsoft.IdentityModel.X509CertificateChain.Build(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509NTAuthChainTrustValidator.Validate(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509SecurityTokenHandler.ValidateToken(SecurityToken token)
at Microsoft.IdentityModel.Tokens.SecurityTokenElement.GetSubject()
at Microsoft.IdentityServer.Service.SecurityTokenService.MSISSecurityTokenService.GetOnBehalfOfPrincipal(RequestSecurityToken request, IClaimsPrincipal callerPrincipal)
--- End of inner exception stack trace ---
at Microsoft.IdentityServer.Service.SecurityTokenService.MSISSecurityTokenService.GetOnBehalfOfPrincipal(RequestSecurityToken request, IClaimsPrincipal callerPrincipal)
at Microsoft.IdentityServer.Service.SecurityTokenService.MSISSecurityTokenService.BeginGetScope(IClaimsPrincipal principal, RequestSecurityToken request, AsyncCallback callback, Object state)
at Microsoft.IdentityModel.SecurityTokenService.SecurityTokenService.BeginIssue(IClaimsPrincipal principal, RequestSecurityToken request, AsyncCallback callback, Object state)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract.DispatchRequestAsyncResult..ctor(DispatchContext dispatchContext, AsyncCallback asyncCallback, Object asyncState)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract.BeginDispatchRequest(DispatchContext dispatchContext, AsyncCallback asyncCallback, Object asyncState)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract.ProcessCoreAsyncResult..ctor(WSTrustServiceContract contract, DispatchContext dispatchContext, MessageVersion messageVersion, WSTrustResponseSerializer responseSerializer, WSTrustSerializationContext
serializationContext, AsyncCallback asyncCallback, Object asyncState)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract.BeginProcessCore(Message requestMessage, WSTrustRequestSerializer requestSerializer, WSTrustResponseSerializer responseSerializer, String requestAction, String responseAction, String
trustNamespace, AsyncCallback callback, Object state)
System.IdentityModel.Tokens.SecurityTokenValidationException: ID4070: The X.509 certificate 'CN=Me, OU=People, O=acme., C=com' chain building
failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. 'A certification chain processed correctly, but one of the CA certificates is not trusted by the policy provider.
at Microsoft.IdentityModel.X509CertificateChain.Build(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509NTAuthChainTrustValidator.Validate(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509SecurityTokenHandler.ValidateToken(SecurityToken token)
at Microsoft.IdentityModel.Tokens.SecurityTokenElement.GetSubject()
at Microsoft.IdentityServer.Service.SecurityTokenService.MSISSecurityTokenService.GetOnBehalfOfPrincipal(RequestSecurityToken request, IClaimsPrincipal callerPrincipal)
thx
Stef71This is perfectly correct on my case I was not adding the root properly you must add the CA and the ADFS as well, which is twice you can see below my results.
on my case was :
PS C:\Users\administrator.domain> $root = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\
cer\SP2K10\ad0001.cer")
PS C:\Users\administrator.domain> New-SPTrustedRootAuthority -Name "domain.ad0001" -Certificate $root
Certificate : [Subject]
CN=domain.AD0001CA, DC=domain, DC=com
[Issuer]
CN=domain.AD0001CA, DC=portal, DC=com
[Serial Number]
blablabla
[Not Before]
22/07/2014 11:32:05
[Not After]
22/07/2024 11:42:00
[Thumbprint]
blablabla
Name : domain.ad0001
TypeName : Microsoft.SharePoint.Administration.SPTrustedRootAuthority
DisplayName : domain.ad0001
Id : blablabla
Status : Online
Parent : SPTrustedRootAuthorityManager
Version : 17164
Properties : {}
Farm : SPFarm Name=SharePoint_Config
UpgradedPersistedProperties : {}
PS C:\Users\administrator.domain> $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\
cer\SP2K10\ADFS_Signing.cer")
PS C:\Users\administrator.domain> New-SPTrustedRootAuthority -Name "Token Signing Cert" -Certificate $cert
Certificate : [Subject]
CN=ADFS Signing - adfs.domain
[Issuer]
CN=ADFS Signing - adfs.domain
[Serial Number]
blablabla
[Not Before]
23/07/2014 07:14:03
[Not After]
23/07/2015 07:14:03
[Thumbprint]
blablabla
Name : Token Signing Cert
TypeName : Microsoft.SharePoint.Administration.SPTrustedRootAuthority
DisplayName : Token Signing Cert
Id : blablabla
Status : Online
Parent : SPTrustedRootAuthorityManager
Version : 17184
Properties : {}
Farm : SPFarm Name=SharePoint_Config
UpgradedPersistedProperties : {}
PS C:\Users\administrator.PORTAL> -
i have to upload video from my hewlett packard t200 camcorder to my mac. but mac won't recognize the camcorder files. i even bought flip4mac by tele stream which so far is useless. please help me use my camcorder with my iMac os mountain lion 10.8.2
i tried to get the installation disc for the camcorder but mac wont' recognize it becaue it is windows based i guess.
i just bought the camcorder a few months ago and when my computer crashed thought i'm finally getting a mac...it's been a costly venture which has resulted in more frustration than before my pc.
now the things i want to use with my mac that i thought would be even simpler...are not even useable...
helpThat camera shoots H.264 in an .avi wrapper.
You will have to transfer the files via the Finder.
Get a free copy of MPEG Streamclip and convert them to QuickTime .mov using the H.264 codec if you are presumably editing in iMovie.
Note that your list of video codecs won't look like mine as I have Final Cut Pro, but H.264 is definitely an option for you. -
I'd like to select print paper size with using AxAcroPDFLib method depend on user
I'd like to select print paper size with using AxAcroPDFLib method depend on user
request. Is it possible? in AxAcroPDFLib?
Is there any method to select print paper size in the C# programming.
Or if you know another method, please introduce how to use.
Thank you for your cooperation always.I am pretty sure that you can only do this from JavaScript or from C/C++ APIs.
-
Why not to use static methods - with example
Hi Everyone,
I'd like to continue the below thread about "why not to use static methods"
Why not to use static methods
with a concrete example.
In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
I created the following class for these "operations" with static methods:
public class KeyboardInput {
private static Robot r;
static {
try {
r = new Robot();
} catch (AWTException e) {
throw new RuntimeException(e + "Robot couldn't be initialized.");
public static void wait(int millis){
r.delay(millis);
public static void copy() {
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_CONTROL);
public static void altTab() {
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_ALT);
// more methods like paste(), tab(), shiftTab(), rightArrow()
}Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
Thanks for any comments in advance,
lemonbostonmaheshguruswamy wrote:
lemonboston wrote:
maheshguruswamy wrote:
I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
If you use a Singleton (and and interface), you can do something like this:
KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class. -
Use wmi methods with powershell to export packages
I'm looking for a way to export packages from a ConfigMgr 2012 ( NOT SP1 ) instance using wmi and powershell. I am aware of the wmi classes under the namespace 'root\sms\XYZ_Site' but I can't find any classes with an 'export' method.
( Please don't tell me to load the SP1 module )
Many thanks!Hi,
Have you figured this out?
Best Regards,
Joyce Li
We
are trying to better understand customer views on social support experience, so your participation in this
interview project would be greatly appreciated if you have time.
Thanks for helping make community forums a great place. -
Using equals method with an array?
Hello all,
I am attempting to use the equals method with an array and keep getting compiling errors. Could you please take a look at my code and tell me where I am going wrong:
if(board[row][col].equals(" "))
str=str + " ";
else
str=str + board[row][col];
Thank you.Hello all,
I am attempting to use the equals method with an
array and keep getting compiling errors. Could you
please take a look at my code and tell me where I am
going wrong:
if(board[row][col].equals(" "))
str=str + " ";
else
str=str + board[row][col];
Thank you.If you could post more of your code, that would be quite helpful... -
Using onFocus method with embedded html
Hi,
I have embedded html in a servlet. I am using a text field to call the onFocus method with the following code:
out.println("<input type='text' name='name' value='0' onFocus='if(this.value=='0')this.value=';'>");
If I was using straight html with no servlet this works fine. When the user clicks on the field the default value is automatically erased.
Why will this not work in a servlet?
I have also tried calling a javascript function. Please note that I successfully use javascript with input type 'button' to render a pop up window with dimensions. So my javascript inside a servlet works elsewhere.
Thanks VERY MUCH for your time
RickI don't think it's the same as I'm doing. Essentially, I have a JEditorPane subclass, which just has a few custom tags in it. I don't need them to be recognized by java, since it will be uneditable, but I just need to know how to convert from the getText() locations to the actual displayed text locations.
Also, when I set the text as text/html, it creates a bunch of extra HTML tags, so it's larger than the original String used to create it. -
problem with download for photo elements 12. got message as I downloaded file 2 (using alt method) that I was miss the "file archive"
Firstly, there's no such thing as Apache 9.3, there's Apache 1 (and subversions) and Apache 2 (and subversions). Your error message -
Oracle-HTTP-Server/1.3.28Shows you're using Apache 1.3.28
Secondly, I'm confused by your comment -
I do not have Apache 9.3 or higher but I think oracle should offer this in its companion CDOracle does offer the Apache server, if you're saying you didn't get it from Oracle then where did your Apache server come from?
Thirdly, I notice from your config file -
ErrorLog "|E:\oracle\product\10.1.0\Companion\Apache\Apache\bin\rotatelogs logs/error_log 43200"That you're piping the logs through rotatelogs, are you sure the logfiles haven't just been renamed? -
Help needed with using network disk with iMovie with NFS or AFP
Hi,
I have iMac with iMovie08 that talks to a remote disk hosted under Linux over a gigabit network using SMB (Samba). It all works ok and I have done a few movies.
Now, I have done some tests with NFS and AFP (AppleTalk) and it seems that these are much faster than SMB.
I then stopped the Samba server and proceeded to setup NFS and also AFP
First NFS,
So I then exported my directory using NFS and I can see everything from my Mac (correct permissions too since I made both user and group IDs the same...). The problem is that when I launch iMovie it shows me the Volume for my external networked disk but it shows it with a little triangle with yellow exclamation and it does not show any of the events (>500GB of events).
If I stop NFS and then switch to AFP I get the same behavior. That is, everything from the Mac works on the AFS mounted disk (copying files back and forth, etc....) but I can't see the contents of the disk from within iMovie
I changed permissions so that anybody can read/write/execute (although there are files that have an '@' sign at the end when I do ls -l on them and I can't remember what that means....)
If I stop NFS and then go back to SMB (Samba) then I am back to a working configuration.
Can I use NFS or AFP with iMovie? What exactly does the yellow triangle mean?
Thanks
Dazed and confused at 330am EST...More timings on smb vs nfs. Note that the big diffs is when sending single large files. The dd cmd was used to simulate 1 hour of DV video which is about 12GB
1.27GB dvd project (twice each, note the variability... I guess because the project has multiple files?):
MEiMac:Movies me$ time cp -r LS2000Berlin.dvdproj /Volumes/bigsmb/
real 0m37.114s
user 0m0.008s
sys 0m4.164s
MEiMac:Movies me$ time cp -r LS2000Berlin.dvdproj /Volumes/bignfs/
real 0m59.351s
user 0m0.009s
sys 0m8.336s
MEiMac:Movies me$ time cp -r LS2000Berlin.dvdproj /Volumes/bignfs/
real 0m40.671s
user 0m0.009s
sys 0m8.205s
MEiMac:Movies me$ time cp -r LS2000Berlin.dvdproj /Volumes/bigsmb/
real 0m41.680s
user 0m0.008s
sys 0m4.094s
Simulated 1 hour video single file:
MEiMac:Movies me$ time dd if=/dev/zero of=/Volumes/bigsmb/1hour bs=16k count=786432
786432+0 records in
786432+0 records out
12884901888 bytes transferred in 443.960166 secs (29022653 bytes/sec)
real 7m23.994s
user 0m3.434s
sys 1m18.900s
MEiMac:Movies me$ time dd if=/dev/zero of=/Volumes/bignfs/1hournfs bs=16k count=786432
786432+0 records in
786432+0 records out
12884901888 bytes transferred in 235.887283 secs (54623131 bytes/sec)
real 3m56.271s
user 0m1.666s
sys 1m56.995s -
Problem with using isAuthenticate method in my applet
Hi everyone
I want to be sure that everytime that I select my applet the secure channel has been opened. I found isAuthenticate method from SecurityService Interface and I think that I can use this method in my applet's select method for this purpose. But when I declare an object as this type like this:
SecurityService Objsecurity;
to use its isAuthenticate method , I'm able to build my code and make the cap file successfully but I recieve error 6F F6 while loading my applet, And I can't find the meaning of this error in GP.
I'll appreciate it if anyone could tell me how can I use this method in my applet .
And the other question is is there any other way to find out the authentication have been done or not?
Best Regards
ShiliHi Pedja,
Thanks for the prompt reply.
I have been following the link you mentioned to create ADF security and successfully implementedthe first part where if i directly give any internal page url it redirects me back to login page.
Instead of using weblogic-sql authenticator, i wanted to manually authenticate the user in loginbean.java where i check the username passowrd against the db.
I had also implemented the method to access username,password mentioned in the following thread
Re: ADF security on my jspx page as login page
Insted of using authentication.login, i am calling the db method to do the validation.
The thing is after my db validation it does redirect me to the success page(menu.jspx). but when i click links on menu.jspx it redirects me back to login page.
so i understand that user is not yet set in the session.
I am stuck at the point how do i code the login.jspx, currently my login.jspx does not have any j_security_check and i think this is what is creating the problem.
while searching for adding jsecurity in jspx i landed on the blog of 2006 and started using that.
Can you please point me to some link which explains how to code login.jspx , i have been trying hard for couple of days.
Thanks again
ash -
Problem with using read() method of BufferedInputStream
Hi,
I m using BufferedInputStream for reading from a socket and I m using read() method for getting data character by character from it . It runs successfully for sometime and then blocks indefinitely and hangs the application. Maybe , when it does not find any data to be read from socket or the LAN connection is broken, it keeps on trying and blocks further processing.
Is there any way to solve this problem so that it does not hangs the application and comes out gracefully ?
Thanx and regards,
Aartee GoyalMost read-methods are blocking, if there is nothing to read.
If you don't want, that your application is blocking, too, the read method has to run in a thread.
The second possibility is, to ask, whether there is something to read
BufferedInputStream bis = ...
if (bis.available() > 0) {
int b = bis.read();
else {
// sleep or break or ???
} -
Problems with using SAXParser.parse with an InputStream
Hello:
I have successfully run the echo01 program from the XML tutorial. I made the following changes to parse the output from a servlet which generates an XML document.
URL recordedSensor = new URL("http://redbd01:8010/servlet/RecordedSensor?vin=1M000000000000001");
URLConnection rsConn = recordedSensor.openConnection();
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( rsConn.getInputStream(), handler);
I get the following errors when I try to run the code.
org.xml.sax.SAXParseException: java.lang.NullPointerException
at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:524)
at org.apache.crimson.parser.Parser2.parse(Parser2.java:305)
at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:442)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:393)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:191)
at ServletInterface.main(ServletInterface.java:29)
I think I have the problem narrowed down to the handlers accessing the class variable out which is a Writer the emit() method uses to output the document. When I replace out.write in emit() with System.out.println() the code works.
I've tried accessing other class variables in the handler methods with similar results.
Anybody encountered similar problems? And what is the solution.
Thanks in advance,
GaryI have the same problem, if you find a solution let me know. I've double checked my objects to make sure their not null, I've checked my constructors in the extended default handler, not really sure where else to look, its such a simple program....
-
NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!
I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
Please reply soon!!! Thanks in advance.class a
private static String aa = "";
public static setVar (String var)
aa = var;
class b
public void init()
a.aa = "try";
public static void main(String b[])
b myB = new b ();
b.init();
hope this help;
bye _drag -
Cannot use Create method with SODataEntity in iOS Native Apps connect to SMP 3.0 SP05
Hi experts,
I am following these blogs:Mobile Application Development Platform for Developers - Native Apps. They are very helpful, thanks Kenichi.
But i have some error when i use Integration gateway.
First, i try method Read, it works perfectly. Then, i try to use method Create, and i meet an error. Here is the error :
Error Domain=NetworkDomain Code=4 "HTTP Response: 403 forbidden" UserInfo=0x7f86d2688040 {NSLocalizedDescription=HTTP Response: 403 forbidden}
I test CRUD method in REST client, and it runs without any errors. I think the difference between Create and Read method is "X-CSRF-Token": Fetch with Read and specific Token with Create. But i do not know how to supply or config "X-CSRF-Token" field when use SOData...
Thanks and Reagrads,
Sao Vu.Hi Sao,
Is your problem solved?
If not, below code may be able to help you for creation using ODataStore:
MAFLogonRegistrationData *data = [[MyLogonHandler shared].logonManager registrationDataWithError:&error];
NSString *baseURL = [NSString stringWithFormat:@"%@", data.applicationEndpointURL];
//opening the store
self.onlineStore = [[OnlineStore alloc] initWithURL:[NSURL URLWithString:baseURL]
httpConversationManager:[MyLogonHandler shared].conversationManager];
[self.onlineStore openStoreWithCompletion:^(BOOL success) {
//Read request after the store is successfully opened
SODataRequestParamSingleDefault* readRequest = [[SODataRequestParamSingleDefault alloc] initWithMode:SODataRequestModeRead resourcePath:@"CollectionName"];
[self.onlineStore scheduleRequest:readRequest delegate:self];
NSString *finishedSubscription = [NSString stringWithFormat:@"com.sap.sdk.request.delegate.finished.%@", readRequest];
//Going for create once read request is success
[[NSNotificationCenter defaultCenter] addObserverForName:finishedSubscription object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
//Creating request for posting the data
SODataRequestParamSingleDefault* insertRequest = [[SODataRequestParamSingleDefault alloc] initWithMode:SODataRequestModeCreate resourcePath:@"CollectionName"];
insertRequest.payload = entityForCreation; //Assigning the payload
[self.onlineStore scheduleCreateEntity:entityForCreation collectionPath:@"Collection
Name" delegate:self options:nil];
//Alternatively you can use [self.onlineStore scheduleRequest:insertRequest delegate:self]; also instead of scheduleCreateEntity
If you want to pass X-CSRF-Token with RequestBuilder, you can use the following code:
//Create request for getting the token
id<Requesting> request = [RequestBuilder requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:endPoint_URL]]];
/*Set user name */
[request setUsername:[[NSUserDefaults standardUserDefaults] objectForKey:@"USERNAME"]];
/*Set password */
[request setPassword:[[NSUserDefaults standardUserDefaults] objectForKey:@"PASSWORD"]];
/*Set the required request headers*/
[request setRequestMethod:@"GET"];
[odp_Request addRequestHeader:@"X-CSRF-Token" value:@"Fetch"];
[odp_Request addRequestHeader:@"X-CSRF-Cookie" value:@"Fetch"];
[request addRequestHeader:@"Content-Type" value:@"application/xml; charset=UTF-8"];
[request addRequestHeader:@"X-SMP-APPCID" value:applicationConnectionID]];
[request addRequestHeader:@"X-SUP-APPCID" value:applicationConnectionID]];
/*Set the delegate to receive the response */
[request setDelegate:self];
/*Set the success listener */
[request setDidFinishSelector:@selector(tokenSuccess:)];
/*Set the failure listener */
[request setDidFailSelector:@selector(tokenFailed:)];
/*Invoke the startAsyncronous API to send the request from client to server asynchronously */
[request startSynchronous];
//In the tokenSuccess method (- (void)tokenSuccess:(Request*)theRequest), you can use the following code to retrieve the token:
token=[[theRequest responseHeaders]objectForKey:@"X-CSRF-TOKEN"];
cookie=[[theRequest responseHeaders]objectForKey:@"SET-COOKIE"];
//Create the request for posting your content to the server
NSString* requestUrls = [NSString stringWithFormat:@"%@SalesOrders%@", endPoint_URL,filterString];
postRequest = [RequestBuilder requestWithURL:[NSURL URLWithString:requestUrls]];
// odp_Request = [ODPRequest requestWithURL:[NSURL URLWithString:requestUrls]];
//id<SDMRequesting> request = [SDMRequestBuilder requestWithURL:[NSURL URLWithString: requestUrls]];
[postRequest setUsername:[[NSUserDefaults standardUserDefaults] objectForKey:@"USERNAME"]];
[postRequest setPassword:[[NSUserDefaults standardUserDefaults] objectForKey:@"PASSWORD"]];
[postRequest setDelegate:self];
[postRequest setRequestMethod:@"POST"];
[postRequest addRequestHeader:@"content-type" value:@"application/atom+xml;type=entry"];
[postRequest addRequestHeader:@"X-SMP-APPCID" value:applicationConnectionID]]; //Assinging the applicationConnectionID value to the request
[postRequest addRequestHeader:@"X-CSRF-Token" value:token]; //Assinging the token value to the request
[postRequest addRequestHeader:@"Cookie" value:cookie]; //Assinging the cookie value to the request
[postRequest appendPostData:[xml dataUsingEncoding:NSUTF8StringEncoding]]; //Appending the body of the request
[postRequest setDidFailSelector:@selector(updaterequestFailed:)]; //Failure delegate method
[postRequest setDidFinishSelector:@selector(updaterequestFinished:)]; //Success delegate method
[postRequest setTimeOutSeconds:200]; //Timeout for request
[postRequest startSynchronous];
Hope this will help you.
Regards,
Dhani
Maybe you are looking for
-
How can I sync my Nokia phone to my Contacts and Calendars without iSync?
Previous to updating to Lion, I would use iSync and a plug-in to sync my Nokia C3-00 to my Address Book Contacts and my iCal Calendar events. Now that I updated, iSync is gone. However, I still need to sync my phone from time to time, is there anyway
-
I can no longer find my bookmarks or a settings/tools tab.
I cannot find a "tools" bar or settings bar and have no bar where my bookmarks use to be. I cannot find any of the open and scroll down lists where my bookmarks, internet options, tools, etc...It's like the whole top bar that I believe was above the
-
How to back up saved application data when moving to new iPhone?
So I've done a fairly extensive search on google trying to figure out how to backup not just my apps, but the saved data within them as well. Most of the stuff I'm finding requires jailbreaking or many steps. I'm coming here to post to see if there i
-
Unable to create a new company
Hi All I have installed sap business one 8.8 But i am unable to create a new company. new button only is missing Regards Farheen
-
Move a file to another computer and back and keep links from breaking?
I have a high school kid neighbor who is going to work on some pages that are on my site, but she does not have the site or access to the server. I want to give her the page on a thumb drive to work on in Dreamweaver on her computer. The pages have