How to add dynamic uuid to apigee proxies? - apigee

What should be of uuid instead of {java.util.UUID.randomUUID()} to get a random UUID in every request sent to backend ?
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true"
name="HeaderAddition">
<DisplayName>HeaderAddition</DisplayName>
<Properties/>
<Add>
<Headers>
<Header name="uuid">{java.util.UUID.randomUUID()}</Header>
</Headers>
</Add>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

I have got the solution .
I have added a Javascript in the preflow to generate the uuid.Then created a assign message policy to have that variable in the request.
JS:
function generateUUID() { // Public Domain/MIT
var d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
d += performance.now(); //use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
var uuid = generateUUID();
context.setVariable('x-apigee-uuid', uuid);
Assign Message Policy:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true"
name="HeaderAddition-123">
<DisplayName>HeaderAddition-123</DisplayName>
<Add>
<Headers>
<Header name="uuid">{x-apigee-uuid}</Header>
</Headers>
</Add>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

Related

Open local pdf file in Xamarin Forms

i'm triying to open a local pdf file in xamarin forms, my code:
var context = Forms.Context;
Java.IO.File javaFile = new Java.IO.File(filePath);
Android.Net.Uri uri = FileProvider.GetUriForFile(context, "myAuth.fileprovider", javaFile);
context.GrantUriPermission(context.PackageName, uri, ActivityFlags.GrantReadUriPermission);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, "application/pdf");
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
Xamarin.Forms.Forms.Context.StartActivity(intent);
i followed several tutorials like this: How to get actual path from Uri xamarin android
But now my problem is that i don't know if the uri is getting the real path for the file:
i got this :
javaFile = "/storage/emulated/0/Download/myReport.pdf" (checked and exist)
uri =
"content://myAuth.fileprovider/external_files/Download/myReport.pdf"
But i got this error on my pdf app "this file cannot be accessed". What i need to change to take the real path of the file? i think the problem is here:
Android.Net.Uri uri = FileProvider.GetUriForFile(context, "myAuth.fileprovider", javaFile);
But don't know what more change in order to work. Thx a lot!
You should set the FileProvider in the application tag of AndroidManifest.xml.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.boxviewcolordemo" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:label="BoxViewColorDemo.Android">
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
Then create file_paths.xml in the xml folder.
file_paths.xml add following code.
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Then in your dependenceService achievement, you should use following code. Note: FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileprovider", file); the second attribute is you package name and ".fileprovider"
[assembly: Dependency(typeof(OpenPDF))]
namespace BoxViewColorDemo.Droid
{
public class OpenPDF : IOpenFile
{
public void OpenPDf(string filePath)
{
var rs = System.IO.File.Exists(filePath);
if (rs)
{
var context = Android.App.Application.Context;
var file = new Java.IO.File(filePath);
var uri = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileprovider", file);
try
{
var intent = new Intent(Intent.ActionView);
intent.AddCategory(Intent.CategoryDefault);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.AddFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
intent.SetDataAndType(uri, "application/pdf");
context.StartActivity(intent);
}
catch (Exception e)
{
Toast.MakeText(context, e.Message, ToastLength.Long).Show();
}
}
}
}
}
And do not forget to grand the read/write permission at the runtime. For testing, you can add following code to the OnCreate method of MainActivity.cs.
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
{
RequestPermissions(new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }, 0);
}
I put the pdf file to the Download folder, my filePath is DependencyService.Get<IOpenFile>().OpenPDf("/storage/emulated/0/Download/test.pdf");
If someone has follow the steps before and still does not works, and the problem continues in the line var uri = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileprovider", file);. Check this too:
1 - Check if it's into Application tag
2 - Check the autority, usually you will use "${applicationId}.provider", but if not works, use a literal, for example myAuth.fileprovider
<application>
...
<provider ..android:authorities="myAuth.fileprovider" ..>
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="#xml/file_paths"></meta-data>
</provider>
</application>
3 - Check the context, var context = Android.App.Application.Context; it's the usually, but if this one does not works, you can try MainActivity.Current, but you need to create first a static var into the MainActivity Class, something like this: public static MainActivity Current = null; and initialize into the OnCreate Method Current = this;. That's was my problem
4 - Check the type of the MimeType of the data, intent.SetDataAndType(uri, "application/pdf");
Thanks again to Leon Lu - MSFT for the answer, this is just an extension for anyone facing the same problem as me.

How to omit null values in JSON AssignMessage payload in APIGEE?

I built a proxy that basically expects a different JSON input object than the one the final endpoint is expecting to receive. So, in order to bridge the request object from one to the other I'm using an AssingMessage policy to transform the json input.
I'm doing something like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Assign-Message-Sample">
<DisplayName>Assign Message-Sample</DisplayName>
<Remove>
<Headers>
<Header name="login_id"/>
<Header name="Authorization"/>
</Headers>
<Payload>true</Payload>
</Remove>
<Set>
<Payload contentType="application/json">
{
"valueA": "{clientrequest.valueA}",
"valueB": "{clientrequest.valueB}",
"valueC": "{clientrequest.valueC}",
"valueD": "{clientrequest.valueD}",
"valueE": "{clientrequest.valueE}",
"valueF": "{clientrequest.valueF}",
}
</Payload>
<Verb>POST</Verb>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>
The problem comes when some of the values are empty. The destination server does not handle properly any empty values (escapes from my control).
My question is: how can I skip entirely a parameter if value is empty?
I'm looking for something like this (or better alternative):
<Payload contentType="application/json">
{
<skip-if-empty name="clientrequest.valueA">
"valueA": "{clientrequest.valueA}",
</skip-if-empty>
"valueB": "{clientrequest.valueB}",
...
}
</Payload>
For what I have found from my research, it seems this is a job for a Javascript Policy.
How is this done?
You basically need to place a javascript policy right before the AssignMessage execution. In the javascript policy you have the freedom to apply all the logic to omit certain parameters if values are not provided.
So for example, say we have already extracted the request values to variables using an ExtractVariables policy. Then, in the Javascript policy we can validate those values and build the resulting JSON object to later store it in another variable that will be picked up by the AssingMessage policy.
javascript policy:
var valueA = context.getVariable("clientrequest.valueA"),
valueB = context.getVariable("clientrequest.valueB"),
valueC = context.getVariable("clientrequest.valueC"),
...
var result = {};
if(valueB) {
result.b = valueB;
}
if(valueA) {
result.a = valueA;
}
if(valueC) {
result.c = valueC;
}
...
context.setVariable("newInput", JSON.stringify(result));
Then our AssignMessage will just pick up the variable we just stored: "newInput" that will contain the complete JSON object string:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Assign-Message-Sample">
<DisplayName>Assign Message-Sample</DisplayName>
<Remove>
<Headers>
<Header name="login_id"/>
<Header name="Authorization"/>
</Headers>
<Payload>true</Payload>
</Remove>
<Set>
<Payload contentType="application/json">
{newInput}
</Payload>
<Verb>POST</Verb>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>
This solution worked fine for me. I hope someone else finds it helpful.

Apigee - key value map - trouble using a variable key

This is pretty basic but I am struggling trying to build/retrieve values from a keyvaluemap. For example given variables X and Y where X=123abc,Y=foo on the first execution and X=456def, Y=bar on the second execution, I would expect to have a key value map where [123abc] -> [foo] and [456def] -> [bar].
However, when I attempt to retrieve the value in variable Z, using either value of X, I always get the last value added: Z=bar. If I delete key X=456def, retrieving key X=123abc returns an error that the key does not exist.
My guess is that only one value is being built into the map, and it is getting put in as "" as if the variable is not set. The override value "true" is replacing it with the last added value. I am sure the variable has a value as it is displayed correctly in the prior policy execution in the trace.
Is there something in the syntax? Any ideas?
I am using the policy below to build the key
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<KeyValueMapOperations mapIdentifier="map1" enabled="true" continueOnError="false" async="false" name="buildmap1">
<DisplayName>build map1</DisplayName>
<FaultRules/>
<Properties/>
<ExclusiveCache>false</ExclusiveCache>
<ExpiryTimeInSecs>-1</ExpiryTimeInSecs>
<InitialEntries/>
<Put override="true">
<Key>
<Parameter>ref="X"</Parameter>
</Key>
<Value ref="Y"></Value>
</Put>
<Scope>organization</Scope>
</KeyValueMapOperations>
I am using the following to retrieve the key
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<KeyValueMapOperations mapIdentifier="map1" enabled="true" continueOnError="false" async="false" name="getmap1">
<DisplayName>get map1</DisplayName>
<FaultRules/>
<Properties/>
<ExclusiveCache>false</ExclusiveCache>
<ExpiryTimeInSecs>-1</ExpiryTimeInSecs>
<InitialEntries/>
<Get assignTo="Z">
<Key>
<Parameter>ref="X"</Parameter>
</Key>
</Get>
<Scope>organization</Scope>
</KeyValueMapOperations>
Please have a look at article on https://community.apigee.com/articles/3384/keyvaluemap-kvmap-operations.html
<Parameter ref='X'></Parameter>
Where X is the variable. But, you were also looking to build a composite key out of two variables
<Parameter ref='X-Y'></Parameter>
will not work. You will need to use a Javascript policy to build that composite key.

405 status code not returning the response properly

I have an http method fault that executes when an incorrect http method is sent in the request.
when I set the status code as 405 ,the request returns a 502 bad gateway .
my fault is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RaiseFault async="false" continueOnError="false" enabled="true" name="invalid-htttp-method-fault">
<DisplayName>invalid htttp method fault</DisplayName>
<FaultRules/>
<Properties/>
<FaultResponse>
<Set>
<Headers/>
<Payload contentType="application/xml">
<Fault>
<Code>405</Code>
<Description>Method Not Allowed</Description>
</Fault>
</Payload>
<StatusCode>405</StatusCode>
<ReasonPhrase>Method Not Allowed</ReasonPhrase>
</Set>
</FaultResponse>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</RaiseFault>
If I change
<StatusCode>405</StatusCode>
<ReasonPhrase>Method Not Allowed</ReasonPhrase>
to
<StatusCode>403</StatusCode>
<ReasonPhrase>Method Not Allowed</ReasonPhrase>
I can see the response payload is returned perfectly . when I use 405 the response returned is :
{"fault":{"faultstring":"Received 405 Response without Allow Header","detail":{"errorcode":"protocol.http.Response405WithoutAllowHeader"}}}
I was able to reproduce the exact issue that you are facing and by doing some more research I found that HTTP 405 response must include an Allow-Header
Try changing your fault policy by adding a header -
<Headers>
<Header name="Allow">YOUR ALLOWED METHODS LIST</Header>
</Headers>
By doing this you should no more be getting the 502 bad gateway and will get what you are expecting as a response.
I hope this helps.
Thanks!
Ah.... Interesting. Response 405 requires an Allow header per the HTTP spec (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). So, the Apigee error is telling you that you need to add an Allow header to your FaultResponse like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RaiseFault async="false" continueOnError="false" enabled="true" name="Fault-405">
<DisplayName>Fault 405</DisplayName>
<FaultRules/>
<Properties/>
<FaultResponse>
<Set>
<Headers>
<Header name="Allow">GET, PUT, POST, DELETE</Header>
</Headers>
<Payload contentType="text/plain">This wasn't supposed to happen</Payload>
<StatusCode>405</StatusCode>
<ReasonPhrase>405 Rules</ReasonPhrase>
</Set>
</FaultResponse>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</RaiseFault>
So add the Allow verbs in the <Set> block and you should be cool.

IDataServiceMetadataProvider - Entities dont show up in $metadata

I am trying to write our own RIA services provider to expose data from a server that I access via ODBC. I follow th eguidelines set out at http://blogs.msdn.com/alexj/archive/2010/03/02/creating-a-data-service-provider-part-9-un-typed.aspx
I have written our own IDataServiceMetadataProvider / IDataServiceQueryProvider pair and get no errors on what i do.
I am putting in a resource set like this:
ResourceType tableType = new ResourceType(
typeof(Dictionary<string, object>),
ResourceTypeKind.EntityType,
null,
"Martini",
table_name,
false
);
tableType.CanReflectOnInstanceType = false;
var prodKey = new ResourceProperty(
"Key",
ResourcePropertyKind.Key |
ResourcePropertyKind.Primitive,
ResourceType.GetPrimitiveResourceType(typeof(int))
);
prodKey.CanReflectOnInstanceTypeProperty = false;
tableType.AddProperty(prodKey);
var prodName = new ResourceProperty(
"Name",
ResourcePropertyKind.Primitive,
ResourceType.GetPrimitiveResourceType(typeof(string))
);
prodName.CanReflectOnInstanceTypeProperty = false;
tableType.AddProperty(prodName);
_MetaDataProvider.AddResourceType(tableType);
_MetaDataProvider.AddResourceSet(new ResourceSet(table_name, tableType));
I see the requests coming in for enumerating the resource sets. I check them there in a breakpoint, and the resource set and the type is there, with all properties.
Still, the output I get is:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
- <service xml:base="http://localhost:2377/MartiniData.svc/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app">
- <workspace>
<atom:title>Default</atom:title>
</workspace>
</service>
And for the $metadata version:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
- <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
- <edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:DataServiceVersion="1.0">
- <Schema Namespace="Martini" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/05/edm">
<EntityContainer Name="Martini" m:IsDefaultEntityContainer="true" />
</Schema>
</edmx:DataServices>
</edmx:Edmx>
The actual metadata for the types never shows up, no error is shown. pretty frustrating. Anyone any idea?
Hmpf. Found.
config.SetEntitySetAccessRule("*", EntitySetRights.All);
was missing in the initialization, so all entities were filtered out ;)

Resources