Alfresco REST API:Data Size Limit? - rest

I am developing REST based webservices in alfresco for data transfer & want to know what is the maximum amount of data i can send/get thru REST protocol?
Any reference would be very helpful.
Regards.

The max amount of data is as large as 2147000000. That's why if your data is large enough it is advisable to stream it to post to your REST service. Here's an example.
Sender/ Uploader Application or Client
var sb = new StringBuilder();
sb.Append("Just test data. You can send large one also");
var postData = sb.ToString();
var url = "REST Post method example http://localhost:2520/DataServices/TestPost";
var memoryStream = new MemoryStream();
var dataContractSerializer = new DataContractSerializer(typeof(string));
dataContractSerializer.WriteObject(memoryStream, postData);
var xmlData = Encoding.UTF8.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length);
var client = new WebClient();
client.UploadStringAsync(new Uri(url), "POST", "");
client.Headers["Content-Type"] = "text/xml";
client.UploadStringCompleted += (s, ea) =>
{
if (ea.Error != null) Console.WriteLine("An error has occured while processing your request");
var doc = XDocument.Parse(ea.Result);
if (doc.Root != null) Console.WriteLine(doc.Root.Value);
if (doc.Root != null && doc.Root.Value.Contains("1"))
{
string test = "test";
}
};
REST Service method
[WebInvoke(UriTemplate = "TestPost", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Xml)]
public string Publish(string market,string sportId, Stream streamdata)
{
var reader = new StreamReader(streamdata);
var res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
Don't forget to put the following configuration settings on your REST Service config file if you don't have this it will throw you an error
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147000000" maxQueryStringLength="2097151" maxUrlLength="2097151"/>
</system.web>
<system.webServer>
........
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="2147000000" maxBufferPoolSize="2147000000" maxBufferSize="2147000000"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>

Related

Magento rest api getting error Request does not match any route

I have created a rest api web service but I am getting error on hitting the url
http://localhost:81/magento/api/rest/category/2
<magento_api>
<messages>
<error>
<data_item>
<code>404</code>
<message>Request does not match any route.</message>
</data_item>
</error>
</messages>
</magento_api>
My api2.xml is:-
<?xml version="1.0"?>
<config>
<api2>
<resource_groups>
<esoft_rescategories translate="title" module="Esoft_Restcategories">
<title>Esoft Restcategories API</title>
<sort_order>11</sort_order>
</esoft_rescategories>
</resource_groups>
<resources>
<esoft_restcategories translate="title" module="Esoft_Restcategories">
<group>esoft_rescategories</group>
<model>esoft_restcategories/api2_restapi</model>
<title>Categories</title>
<sort_order>11</sort_order>
<privileges>
<admin>
<create>1</create>
<!--<retrieve>1</retrieve>
<update>1</update>
<delete>1</delete>-->
</admin>
<guest>
<retrieve>1</retrieve>
<!--<create>1</create>
<update>1</update>
<delete>1</delete>-->
</guest>
</privileges>
<attributes>
<category_id>Category ID</category_id>
<name>Name</name>
<parent_id>Category Parent ID</parent_id>
<child_id>Category Child List</child_id>
<active>Active</active>
<level>Level</level>
<position>Position</position>
</attributes>
<routes>
<route_entity>
<route>/categories/:cat_id</route>
<action_type>entity</action_type>
</route_entity>
<route_collection>
<route>/categories</route>
<action_type>collection</action_type>
</route_collection>
</routes>
<versions>1</versions>
</esoft_restcategories>
</resources>
</api2>
</config>
My version file for guest is:-
<?php
class Esoft_Restcategories_Model_Api2_Restapi_Rest_Guest_V1 extends Esoft_Restapi_Model_Api2_Restapi {
/**
* Retrieve list of category list.
*
* #return array
*/
protected function _retrieveCollection()
{
$ruleId = $this->getRequest()->getParam('cat_id');
// $cat_mod = Mage::getModel('catalog/category')->load($ruleId)->toArray();
$cats = Mage::getModel('catalog/category')->load($ruleId);
$subcats = Mage::getModel('catalog/category')->load($ruleId)->getChildren();
$cur_category = array();
$node['category_id'] = $ruleId;
$node['name'] = $cats->getName();
$node['parent_id'] = $cats->getParentId();
$node['child_id'] = $subcats;
if($cats->getIsActive()){
$node['active'] = 1;
}else{
$node['active'] = 0;
}
$node['level'] = $cats->getLevel();
$node['position'] = $cats->getPosition();
$cur_category[] = $node;
// $subcats = Mage::getModel('catalog/category')->load($ruleId)->getAllChildren();
// $subcats = Mage::getModel('catalog/category')->load($ruleId)->getChildren();
if($subcats != '')
{
foreach(explode(',',$subcats) as $subCatid)
{
$_category = Mage::getModel('catalog/category')->load($subCatid);
$childcats = Mage::getModel('catalog/category')->load($subCatid)->getChildren();
$node['category_id'] = $subCatid;
$node['name'] = $_category->getName();
$node['parent_id'] = $_category->getParentId();
$node['child_id'] = $childcats;
if($_category->getIsActive()){
$node['active'] = 1;
}else{
$node['active'] = 0;
}
$node['level'] = $_category->getLevel();
$node['position'] = $_category->getPosition();
$cur_category[] = $node;
}
}
return $cur_category;
}
}
Please let me know how to fix this error.
Also let me know on what basis we define routes.
Simple answer for those searching for cause of this error:
Request does not match any route
Is that you are posting the wrong METHOD such as GET/POST/PUT/DELETE.
It could also be the path of the API url itself is wrong.
As per your description your url format is wrong (route miss matching in given url).
<route>/categories/:cat_id</route>
^^^^^^^^^
So you need to change the url like below
http://localhost:81/magento/api/rest/categories/2

Does ColdFusion 11 support body content for HTTP DELETE verb

The below script block on ColdFUsion 11 has GetHttpRequestData().content as hello
If I change the verb to DELETE it is empty.
So ...
Does ColdFusion not support this when making requests via cfhttp?
Is this the wrong way?
Is there a workaround?
Code:
cfhttp(method="POST", charset="utf-8", url="http://x/showrequest.cfm", result="result" ) {
cfhttpparam(name="body", type="body", value="hello");
}
writeOutput(result.filecontent);abort;
Work around was to use java (shiver). Im sure there are helper libs to do this more succinctly but here it is.
<cfscript>
var u = createObject("java", "java.net.URL").init("https://api.cloudflare.com/client/v4/zones/#site.zoneId#/purge_cache");
var req = u.openConnection();
req.setRequestMethod("DELETE");
req.setDoOutput(true);
req.setRequestProperty("Content-Type", "application/json" );
req.setRequestProperty("X-Auth-Email", "xxxxx" );
req.setRequestProperty("X-Auth-Key", "xxxx" );
var os = req.getOutputStream();
os.write(javaCast("string",'{"files":#serializeJSON(urls)#}').getBytes("UTF-8"));
os.close();
ret = req.getResponseMessage();
var i = req.getInputStream();
var br = createObject("java", "java.io.BufferedReader").init(createObject("java", "java.io.InputStreamReader").init(i));
var sb = createObject("java", "java.lang.StringBuilder").init();
var line = br.readLine();
while(!isNull(line)){
sb.append(line);
line = br.readLine();
}
req.disconnect();
</cfscript>
<cfdump var="req.getResponseCode() = #req.getResponseCode()#">
<cfdump var="#ret#">
<cfdump var="#sb.toString()#">

How to set content-Type on WCF request

My issue is that a testing app like Google Postman (awesome tool, found here) can send the message.
When I send the message it's always refused (the exact same message) because nonse is 'expired'.
So there must be something different about how I'm sending it...
There is... Content-Type is different, for one... but not sure if that's why...
I've seen some hints about accessing endpoint behaviours like:
var whb = client.ChannelFactory.Endpoint.Behaviors.Find<WebHttpBehavior>();
But that only allows me to choose between xml and json.
whb.AutomaticFormatSelectionEnabled = false;
whb.DefaultOutgoingRequestFormat = WebMessageFormat.Xml;
I have a wsdl:
http://caqh.org/SOAP/WSDL/CORERule2.2.0.wsdl
I need to call the WCF service's RealTimeTransaciton with headers that that are:
Content-Type: application/soap+xml;charset=UTF-8;
Currently, by default I suppose, the call includes headers;
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
and Content-Type doesn't seem to be set.
So I tried to affect the headers of the request...
var addressHeaders = new List<AddressHeader> {
AddressHeader.CreateAddressHeader("Content-Type", "", "application/soap+xml;charset=UTF-8;"),
AddressHeader.CreateAddressHeader("Cache-Control", "", "no-cache"),
AddressHeader.CreateAddressHeader("Accept", "", "application/soap+xml;charset=UTF-8;")
};
var client = new CORETransactionsClient(binding, new EndpointAddress(new Uri(url),addressHeaders.ToArray()));
But to my surprise, the result of this is that these 'headers' are added within the soap Envelope headers, and not the headers for the transport!
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<Content-Type>application/soap+xml;charset=UTF-8;</Content-Type>
<Cache-Control>no-cache</Cache-Control>
<Accept>application/soap+xml;charset=UTF-8;</Accept>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
etc.... lol
My web.config service model:
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CoreSoapBinding">
<textMessageEncoding messageVersion="Soap12" writeEncoding="UTF8" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://my_vendor_url_for_service_that_is_Axis2_based" binding="customBinding"
bindingConfiguration="CoreSoapBinding" contract="CoreRule.CORETransactions"
name="CoreSoapPort"
endpointConfiguration="">
</endpoint>
</client>
</system.serviceModel>
How I call:
var msg = Create270X12Message(requestReferenceId, senderId, receiverId, requestDateStr, productionCall, prettyOutput);
var envelope = new COREEnvelopeRealTimeRequest
{
CORERuleVersion = "2.2.0",
Payload = string.Format("<![CDATA[{0}]]>", Convert.ToBase64String(Encoding.UTF8.GetBytes(msg))),
PayloadID = requestReferenceId.ToString(),
PayloadType = CoreRule2PayloadType_270_5010,
ProcessingMode = CoreRule2ProcessingMode_270_5010,
ReceiverID = receiverId,
SenderID = senderId,
TimeStamp = requestDateStr
};
var client = CreateRealTimeOnlineProxy(urlMissouiri, username, password, requestDateStr);
var response = client.RealTimeTransaction(envelope);
How can I add my collection of headers to the request itself, instead of the SOAP Envelope headers?

How to call CQ author URL from a standalone code

I am trying to hit URL in cq Author instance from my standalone code. The URL looks like — http://<somehost>:<someport>//libs/dam/gui/content/reports/export.json
Below is the code:
URL url = new URL(newPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15 * 10000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
But I got a 401 error, which is expected, as I'm not passing any authentication information — hence Sling says:
getAnonymousResolver: Anonymous access not allowed by configuration - requesting credentials.
How can I get resolve this?
You may use Basic HTTP authentication. Adding it to the HttpURLConnection is little awkward:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "admin".toCharArray());
}
});
Consider using Apache HttpClient:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin");
DefaultHttpClient authorizedClient = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = authorizedClient.execute(request);
InputStream stream = response.getEntity().getContent();

force.com callout exception Unable to tunnel through proxy

We make a callout from one Salesforce org to another Salesforce org using the REST API. That worked until end of november. We didn't make any changes at the affected classes or configuration.
Now, while sending a request to the rest api a callout exception will be thrown with the message : "Unable to tunnel through proxy. Proxy returns "HTTP/1.0 503 Service Unavailable".
The authorisation to the rest api is done by session id.
Does anyone have any idea what the problem is?
Here the code snipped:
final String WS_ENDPOINT = 'https://login.salesforce.com/services/Soap/c/24.0';
final String REST_ENDPOINT = 'https://eu2.salesforce.com/services/apexrest/UsageReporterService';
final String USERNAME = '*****';
final String PASSWORD = '*****';
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setMethod('POST');
req.setEndpoint(REST_ENDPOINT);
req.setHeader('Content-Type', 'application/json');
req.setTimeout(60000);
HTTP hLogin = new HTTP();
HTTPRequest reqLogin = new HTTPRequest();
reqLogin.setMethod('POST');
reqLogin.setEndpoint(WS_ENDPOINT);
reqLogin.setHeader('Content-Type', 'text/xml');
reqLogin.setHeader('SOAPAction', 'login');
reqLogin.setTimeout(60000);
reqLogin.setCompressed(false);
// get a valid session id
String sessionId;
String loginSoap = '<?xml version="1.0" encoding="UTF-8"?>';
loginSoap += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com">';
loginSoap += '<soapenv:Body>';
loginSoap += '<urn:login>';
loginSoap += '<urn:username>' + USERNAME + '</urn:username>';
loginSoap += '<urn:password>' + PASSWORD + '</urn:password>';
loginSoap += '</urn:login>';
loginSoap += '</soapenv:Body>';
loginSoap += '</soapenv:Envelope>';
reqLogin.setBody(loginSoap);
HTTPResponse respLogin;
try {
respLogin = hLogin.send(reqLogin);
} catch(CalloutException c){
return null;
}
System.debug('++++++'+respLogin.getStatus() + ': ' + respLogin.getBody());
Dom.Document doc = new Dom.Document();
doc.load(respLogin.getBody());
Dom.XMLNode root = doc.getRootElement();
String ns = root.getNamespace();
Dom.XMLNode bodyEl = root.getChildElements()[0];
if(bodyEl.getChildElements()[0].getName().equals('loginResponse')){
sessionId = bodyEl.getChildElements()[0].getChildElement('result', ns).getChildElement('sessionId', ns).getText();
}
// finished getting session Id
if(sessionId != null){ // login was successfull
req.setHeader('Authorization', 'Bearer ' + sessionId);
// serialize data into json string
UsageReporterModel usageReporterData = new UsageReporterModel();
String inputStr = usageReporterData.serialize();
req.setBody('{ "usageReportData" : ' + inputStr + '}');
// fire!
HTTPResponse resp;
try {
resp = h.send(req);
} catch(CalloutException c){
return null;
}
}
I suspect this will relate to a change of IP addresses for one of the org's which haven't been whitelisted correctly (or added to the "network access" object). With it being Salesforce to Salesforce I would hope that Salesforce.com support can assist?