ibm connections assigning file to folder - ibm-connections

I have a problem when I try to assign a file with folder, the file and folder exist in the system but when I use the method for upload the folder of the file the response it's success but the file not figure into the folder.
I use the method
POST /basic/api/collection/{collection-id}/feed
in the collection-id I change for the folder UUID but don't works.
you know how assign a file to folder?
System.out.println("Uploading " + fileName + " in " + parentFolderName);
Abdera abdera = new Abdera();
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
//Entry
entry.setTitle(parentFolderName);
entry.setId(parentFolderUUID);
InputStream in = req.getInputStream();
entry.setContent("application/pdf");
entry.setLanguage("en");
AbderaClient abderaClient = new AbderaClient(abdera);
abderaClient.addCredentials(Utils.configJson.getString("connectionsServerURL"), null, null, new UsernamePasswordCredentials(connectionsUser, connectionsPassword));
//Nonce
String nonceUrl = "https://connectionsww.demos.ibm.com/files/basic/api/nonce";
ClientResponse respNonce = abderaClient.get(nonceUrl);
StringWriter writerNonce = new StringWriter();
IOUtils.copy(respNonce.getInputStream(), writerNonce, "UTF-8");
String nonce = writerNonce.toString();
//Multipart-post options
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setSlug(parentFolderUUID);
options.setContentType("multipart/mixed");
options.setAcceptLanguage("en");
options.setHeader("X-Update-Nonce", nonce);
fileURL = fileURL + "?X-Update-Nonce=" + nonce;
ClientResponse resp = abderaClient.post(fileURL, entry);

based on the method signature, I think you are missing two items:
One
Content-Type header should be
Content-Type: application/atom+xml
Two payload of itemid (the id there is the id of the file I want in the folder/collection).
<feed xmlns="http://www.w3.org/2005/Atom">
<entry>
<itemId xmlns="urn:ibm.com/td">aca70bd1-0925-42c1-8196-b1c3042178a6</itemId>
</entry>
</feed>

I found the solution for the answer of #Paul, the final code it's there.
Abdera abdera = new Abdera();
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
//Entry
entry.setUpdated(new java.util.Date());
entry.setTitle(parentFolderName);
entry.setId(parentFolderUUID);
InputStream in = req.getInputStream();
entry.setContent("application/atom+xml");
entry.setLanguage("en");
AbderaClient abderaClient = new AbderaClient(abdera);
abderaClient.addCredentials(Utils.configJson.getString("connectionsServerURL"), null, null, new UsernamePasswordCredentials(connectionsUser, connectionsPassword));
System.out.println("added abdera client credentials");
//Nonce
String nonceUrl = "https://connectionsww.demos.ibm.com/files/basic/api/nonce";
ClientResponse respNonce = abderaClient.get(nonceUrl);
StringWriter writerNonce = new StringWriter();
IOUtils.copy(respNonce.getInputStream(), writerNonce, "UTF-8");
String nonce = writerNonce.toString();
//Multipart-post options
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setSlug(parentFolderUUID);
options.setContentType("application/atom+xml");
options.setAcceptLanguage("en");
options.setHeader("itemId", docUUID);
fileURL = fileURL + "?itemId="+docUUID;
System.out.println("fileURL+++++: " + fileURL);
ClientResponse resp = abderaClient.post(fileURL, entry, options);

Related

No suitable HttpMessageConverter found error while executing rest service that takes multipart parameters

I am using Spring Integration in my project. I am trying to execute a rest service which takes multipart/formdata input parameters. I am using int-http:outbound-gateway to execute rest service. The following is the code:
<int:channel id="PQcreateAttachment-Rest-Channel" />
<int:chain input-channel="PQcreateAttachment-Rest-Channel" output-channel="PQcreateAttachment-StoredProcedure-Router" >
<int:header-filter header-names="accept-encoding"/>
<int:service-activator ref="httpOutboundGatewayHandler" method="buildMultipartHttpOutboundGatewayRequest" />
<int-http:outbound-gateway url-expression="headers.restResourceUrl"
http-method-expression="headers.httpMethod"
extract-request-payload="true"
>
</int-http:outbound-gateway>
<int:service-activator ref="msgHandler" method="buildMessageFromExtSysResponse" />
</int:chain>
But I am getting the following error when I execute the above code.
Caused by: org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.integration.message.GenericMessage] and content type [application/x-java-serialized-object]
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:665)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:481)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:460)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:409)
at org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler.handleRequestMessage(HttpRequestExecutingMessageHandler.java:372)
... 121 more
Here is the java code that prepares my multipart request:
public Message<?> buildMultipartHttpOutboundGatewayRequest(Message<?> inMessage) throws Exception{
logger.debug(" ************** buildMultipartHttpOutboundGatewayRequest Start *************************");
String inMsgPayload = (String)inMessage.getPayload();
SOAXml soaXml = parseSOAXml(inMsgPayload);
String restURL = null;
String contentType = null;
String acceptHdr = null;
String userId = null;
String password = null;
String businessAreaName = null;
String typeName = null;
String attachmentLocation = null;
String httpMethod = null;
Message<?> outMessage = null;
MessageHeaders inMsgHdrs = null;
MessageBuilder<?> msgBuild = null;
String authorization = null;
//TODO: File location needs to be changed to standard one
String fileLocation = "C:\\source.xml";
//if we reach here means, it is AWD system
restURL = getAwdSOAService(soaXml);
Document document = XmlParserUtil.convertString2Document(inMsgPayload);
userId = XmlParserUtil.getNodeValue(document,"//userId");
password = XmlParserUtil.getNodeValue(document,"//PQcreateAttachment/password");
businessAreaName = XmlParserUtil.getNodeValue(document,"//businessAreaName");
typeName = XmlParserUtil.getNodeValue(document,"//typeName");
httpMethod = XmlParserUtil.getNodeValue(document,"//METHOD");
attachmentLocation = XmlParserUtil.getNodeValue(document,"//attachmentLocation");
//Construct source xml
//Creating document
Document sourceDocument = DocumentHelper.createDocument();
Element sourceInstance = sourceDocument.addElement("createSourceInstance");
sourceInstance.addAttribute("xmlns", "http://www.dsttechnologies.com/awd/rest/v1");
Element orderItem=sourceInstance.addElement("businessAreaName");
orderItem.setText("SAMPLEBA");
Element orderItemDesc=sourceInstance.addElement("typeName");
orderItemDesc.setText("SAMPLEST");
// create source xml file
XmlParserUtil.createXMLFileUsingDOM4J(sourceDocument, fileLocation);
authorization = getBasicAuthorization(userId,password);
Resource source = new ClassPathResource(fileLocation);
Resource attachment = new ClassPathResource(attachmentLocation);
Map<String, Object> multipartMap = new HashMap<String, Object>();
multipartMap.put("source", source);
multipartMap.put("attachment", attachment);
logger.info("Created multipart request: " + multipartMap);
inMessage = buildMessageForMultipart(multipartMap);
// contentType = csProps.getHttpAwdContentTypeValue();
acceptHdr = csProps.getHttpAwdAcceptTypeValue() ;
// authorization = getBasicAuthorization(soaXml.getUserid(),decriptPassword(soaXml.getPassword()));
inMsgHdrs = inMessage.getHeaders();
msgBuild = MessageBuilder.withPayload(inMessage).copyHeaders(inMsgHdrs);
msgBuild.removeHeader("Content-Encoding");
msgBuild.removeHeader("accept-encoding");
msgBuild.setHeader(csProps.getHttpUrlHdr(), restURL);
msgBuild.setHeader(csProps.getHttpMethodHdr(), httpMethod);
msgBuild.setHeader(csProps.getHttpAuthorizatonHdr(),authorization );
// msgBuild.setHeader(csProps.getHttpContentTypeHdr(), contentType);
// msgBuild.setHeader(csProps.getHttpAcceptTypeHdr(),acceptHdr);
outMessage = msgBuild.build();
logger.debug(" ************** buildHttpOutboundGatewayRequest End*************************");
logger.debug(outMessage);
logger.debug(" ************************************************************************");
return outMessage;
}
Any ideas on what's wrong here?
Your problem is because you wrap one message to another.
What your buildMessageForMultipart(multipartMap); does?
I'm sure the simple map as payload and those header would be enough.
Not sure what is the point to wrap one message to another.

accessing data from service bus

I am trying to connect to servicebus and getting data from it, it seems since I've got the token I must reuse it evertime I make a request what's wrong with this code?here is the error I've got at the last
line The remote server returned an error: (401) Unauthorized.
//sample usage string mydata1 = string.Format(Constants.myData, brfId);
public static readonly myData= "https://sdgsdg.servicebus.windows.net/sgsdg/gdgsg/{0}";
//sample usage - string agendaByBriefingDetailIdURI = string.Format(Constants.myData2 BriefingID, accessCode);
public static readonly string myData2= "https://sdgsg.servicebus.windows.net/sdg/dgsg/{0}/{1}";
string SCOPE = "http://lalalalala.servicebus.windows.net/";
string WRAP_PASSWORD = "lalalalalala"
string WRAP_USERNAME = "lalalala";
string ACS_NAMESPACE = "lalalalala";
WebClient client = new WebClient();
client.BaseAddress = string.Format("https://{0}.accesscontrol.windows.net", ACS_NAMESPACE);
NameValueCollection values = new NameValueCollection();
values.Add("wrap_name", WRAP_USERNAME);
values.Add("wrap_password", WRAP_PASSWORD);
values.Add("wrap_scope", SCOPE);
// WebClient takes care of the URL Encoding
byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
// the raw response from ACS
string response = Encoding.UTF8.GetString(responseBytes);
string token = response.Split('&').Single(x => x.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase)).Split('=')[1];
string decodedToken = HttpUtility.UrlDecode(token);
string.Format("WRAP access_token=\"{0}\"", HttpUtility.UrlDecode(token));
WebClient webClient = new WebClient();
webClient.Headers["Authorization"] = string.Format("WRAP access_token=\"{0}\"", HttpUtility.UrlDecode(token));
string returnString = webClient.DownloadString(string.Format(mystaticre, 10));

PublishingRolloutImage not persisting on Update();

I have a list, that has three fields: Title, PublishingRollupImage and Description.
I want to upload the image to the library SiteCollectionImages and reference it on the list.
I'm able to upload the file to the folder SiteCollectionImages, and get it's url.
I'm also able to insert the item in the list "MyList", but the PublishingRolloutImage won't persist after the Update() method. I already tried to set the constructor for the ImageFieldValue, like this:
new ImageFieldValue("<img src='test.jpg' />");
but it didn't work.
Here's my code:
using (var site = new SPSite(SPContext.Current.Site.ID))
using (var web = site.OpenWeb())
{
var folder = web.GetFolder("SiteCollectionImages");
var file = folder.Files.Add(fileName, file, true);
folder.Update();
var list = web.Lists["MyList"];
var item = list.Items.Add();
item["Title"] = "MyItemTitle";
item["PublishingRollupImage"] = new ImageFieldValue { ImageUrl = file.Url };
item["Description"] = "MyDescription";
item.Update();
}
What i'm doing wrong?
After a lot of trial and error, i found out that i was doing two things wrong:
this:
item["PublishingRollupImage"] = new ImageFieldValue { ImageUrl = file.Url };
was supposed to be like this:
var image = item["PublishingRollupImage"] as ImageFieldValue ?? new ImageFieldValue();
image.ImageUrl = String.Format("/{0}", file.Url);
item["PublishingRollupImage"] = image;
and file.Url needs to start with a slash. If it doesn't start with a slash, it will break after the Update(); method. That's the reason for the String.Format up there.

Uploading files to a SharePoint document library with metadata

I am using the following code to upload a file to a SharePoint Document Library but it's not attaching the metadata:
private void UploadFileToSharePoint(string strInputFileName, string sDocLibraryName)
{
SPWeb site = SPContext.Current.Web;
SPList myList = site.Lists[sDocLibraryName];
string destFileUrl = myList.RootFolder.ServerRelativeUrl + #"/New.txt";
site.AllowUnsafeUpdates = true;
// FileStream fileStream = File.Open(strInputFileName, FileMode.Open);
byte[] strm = File.ReadAllBytes(strInputFileName);
// newFile.CheckIn("File added");
//SPListItem item = newFile.Item;
//item.File.CheckOut();
Hashtable ht = new Hashtable();
ht.Add("Status Indicator", "hello");
ht.Add("Status Description", Description.Text);
ht.Add("Status", "Delayed");
//item.Update();
//item.File.CheckIn("File with metadata");
myList.RootFolder.Files.Add(destFileUrl,strm,ht, true/*overwrite*/);
myList.Update();
}
I am using this function call:
UploadFileToSharePoint(#"C:\check.txt",
"Project Status" /* name of Dc Library*/ );
I don't see where you add the metadata, i see you filling a hashtable and do nothing with it

SP 2010 Attach File Client Object Model

I have created some code to create a list item programmatically. Now I would like to attach a file to the list. I'm getting a 401 error: unauthorized. I have set the credentials which works for creating the item but not attaching the file. Any ideas?
Dim credentials As New System.Net.NetworkCredential(MyUser, MyPassword, MyDomain)
Dim SiteUrl As String = MyUrl
Dim clientContext As New ClientContext(SiteUrl)
clientContext.Credentials = credentials
Dim list As List = clientContext.Web.Lists.GetByTitle(MyList)
Dim itemCreateInfo As New ListItemCreationInformation()
Dim listItem As Microsoft.SharePoint.Client.ListItem = list.AddItem(itemCreateInfo)
listItem("Title") = "Test Programmatically Create Item"
listItem("Subject") = "TEST"
listItem("Class") = "101"
listItem("Section") = "20"
listItem.Update()
listItem.Update()
clientContext.ExecuteQuery()
Dim fStream As Stream = File1.PostedFile.InputStream
Dim attachmentPath As String = String.Format("/{0}/Lists/{1}/Attachments/{2}/{3}", MySite, MyList, listItem.Id, MyFileName)
'-- This Line Fails with the following error
'-- The remote server returned an error: (401) Unauthorized.
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, attachmentPath, fStream, True)
I know setting the credentials is correct because if I don't set them then I get this error trying to create the list item.
Any thoughts are greatly appreciated or if there is a better way to attach a file to a list item please let me know.
Thanks!
It worked for me.
I first read the file that needs to be uploaded into the memory and used MemoryStream to pass the file to SaveBinaryDirect.
static void moveFileFromOneFarmToAnother()
{
string srcSiteUrl = "SourceSiteUrl";
string srcFileRelUrl = "ReletiveUrlOfTheListItemAttachment";
ClientContext srcCC = new ClientContext(srcSiteUrl);
Web srcWb = srcCC.Web;
srcCC.Load(srcWb, w => w.ServerRelativeUrl);
srcCC.ExecuteQuery();
FileInformation fI = Microsoft.SharePoint.Client.File.OpenBinaryDirect(srcCC, srcWb.ServerRelativeUrl + srcFileRelUrl);
byte[] buffer = new byte[16 * 1024];
byte[] byteArr;
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = fI.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
byteArr = ms.ToArray();
}
MemoryStream mnm = new MemoryStream(byteArr);
srcCC.ExecuteQuery();
string desSiteUrl = "DestinationSiteUrl";
string desFileUrl = "ReletiveUrlOfTheListItemAttachment";
ClientContext cc = new ClientContext(desSiteUrl);
Web wb = cc.Web;
cc.Load(wb, w1 => w1.ServerRelativeUrl);
cc.ExecuteQuery();
Microsoft.SharePoint.Client.File.SaveBinaryDirect(cc, wb.ServerRelativeUrl + desFileUrl, mnm, true);
cc.ExecuteQuery();
}
Take a look at the following link. This should point you in the right direction.
http://www.sharepointdevwiki.com/display/public/Creating+a+List+Item+instance+programmatically+using+the+object+model?focusedCommentId=7897226
You could also take a look at SPSecurity.RunWithElevatedPrivileges().
Good luck

Resources