Returning JSON Arrays in customAttributes - ibm-mobilefirst

Following on from my previous question, I can return a list of groups in the custom attributes section, however I'd like to know what I need to do to return them in a std JSON structure.
If I send back a Java List
HashMap<String, Object> customAttributes = new HashMap<String, Object>();
customAttributes.put("AuthenticationDate", new Date());
List<String> groups = new ArrayList<String>();
groups.add("Users");
groups.add("Managers");
customAttributes.put("Groups", groups);
UserIdentity identity = new UserIdentity(loginModule, USERNAME, "Fred Flintstone", null, customAttributes, PASSWORD);
Then the client receives
{"Groups":"[Users, Managers]","AuthenticationDate":"Tue Nov 26 12:07:37 EST 2013"}
If I add the groups in a hashMap
List<Map<String, Object>> groups = new ArrayList<Map<String, Object>>();
HashMap<String, Object> groupMap1 = new HashMap<String, Object>();
groupMap1.put("id", "Users");
groups.add(groupMap1);
HashMap<String, Object> groupMap2 = new HashMap<String, Object>();
groupMap2.put("id", "Managers");
groups.add(groupMap2);
customAttributes.put("Groups", groups);
UserIdentity identity = new UserIdentity(loginModule, USERNAME, "Fred Flintstone", null, customAttributes, PASSWORD);
I get the following response in the client
"attributes":{"Groups":"[{id=Users}, {id=Managers}]","AuthenticationDate":"Tue Nov 26 12:13:40 EST 2013"}
What I'd really like to get is something like this
"attributes":{"Groups":[{"id" : "Users"}, {"id" :"Managers"}],"AuthenticationDate":"Tue Nov 26 12:13:40 EST 2013"}

In order to do this, you'll need to convert the groups HashMap into a JSON object before putting it into your attributes HashMap.
Something like:
...
groups.add(groupMap1);
groups.add(groupMap2);
customAttributes.put("Groups", JSONObject(groups));
The syntax for converting the HashMap to a JSONObject will vary depending on which JSON library your project has access to. If it does not have a method built in, then you will have to manually loop through your HashMap in order to convert it into a proper JSONObject.
Edit:
Since the groups object is being passed in as a string, you can use JSON.parse to convert it into a JSON object.
function getSecretData(){
var user = WL.Server.getActiveUser();
var attributes = user.attributes;
var groups = JSON.parse(attributes.Groups);
return {
groups: groups
};
}

Related

.Net-Core get HttpBrowserCapabilities from httpContext

I want to use the HttpBrowserCapabilities in .net-core. I tried it following way:
var userAgent = httpContext.Request.Headers["user-agent"];
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
var mobileString = userBrowser.IsMobileDevice ? "(mobil)" : string.Empty;
var browserString = $"{userBrowser.Browser} version {userBrowser.Version} {mobileString} OS: {userBrowser.Platform}";
But an InvalidCastException is thrown. How ca i get this code retun the right values?
Got it!
userAgent is of the type Microsoft.Extensions.Primitives.StringValues.
But HttpBrowserCapabilities expects a string as input parameter.
Therefore i had to check if userAgent contains a value (userAgent.Any()) and use the following code
var userBrowser = new HttpBrowserCapabilities {Capabilities = new Hashtable {{string.Empty, userAgent.First()}}};

How to decode JWT (Header and Body) in java using Apache Commons Codec?

I am looking decode the following JWT using Apache Commons Codec. How we can do that ?
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZ
WxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw
This should retrieve Header, Body and Signature part. Whats the code ?
Here you go:
import org.apache.commons.codec.binary.Base64;
#Test
public void testDecodeJWT(){
String jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZWxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw";
System.out.println("------------ Decode JWT ------------");
String[] split_string = jwtToken.split("\\.");
String base64EncodedHeader = split_string[0];
String base64EncodedBody = split_string[1];
String base64EncodedSignature = split_string[2];
System.out.println("~~~~~~~~~ JWT Header ~~~~~~~");
Base64 base64Url = new Base64(true);
String header = new String(base64Url.decode(base64EncodedHeader));
System.out.println("JWT Header : " + header);
System.out.println("~~~~~~~~~ JWT Body ~~~~~~~");
String body = new String(base64Url.decode(base64EncodedBody));
System.out.println("JWT Body : "+body);
}
The output below:
------------ Decode JWT ------------
~~~~~~~~~ JWT Header ~~~~~~~
JWT Header : {"alg":"HS256"}
~~~~~~~~~ JWT Body ~~~~~~~
JWT Body : {"sub":"test","roles":"ROLE_ADMIN","iss":"myself","exp":1471086381}
Here is a non-package-import way:
java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
String[] parts = jwtToken.split("\\."); // split out the "parts" (header, payload and signature)
String headerJson = new String(decoder.decode(parts[0]));
String payloadJson = new String(decoder.decode(parts[1]));
//String signatureJson = new String(decoder.decode(parts[2]));
REGARDLESS (of this alternative to org.apache.commons.codec.binary.Base64 SiKing'sanswer )... you may want to also push those json fragments to pojo's.
You can then take those json fragments and turn them into pojo.
The headers are "dynamic" (as in, you don't know all the header-names beforehand), so you probably want to convert to Key Value pairs (aka "Map" in java)
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JwtTokenHeaders {
private final Map<String, Object> jsonMap; // = new HashMap<String, Object>();
public JwtTokenHeaders(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
//String jsonString = "{\"name\":\"JavaInterviewPoint\", \"department\":\"blogging\"}";
//Map<String, Object> jsonMap = new HashMap<String, Object>();
try {
// convert JSON string to Map
this.jsonMap = mapper.readValue(jsonString,
new TypeReference<Map<String, String>>() {
});
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
#Override
public String toString() {
return org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(this);
}
}
the payload (aka, the body) is more well-defined, so you can map to a pojo..... you can take the json and create a matching pojo here:
http://pojo.sodhanalibrary.com/
after you use an online tool (or hand craft the pojo youself)..to create something like "MyPojo(.java)"....
you'll end up with something like this:
//import com.fasterxml.jackson.databind.DeserializationFeature;
//import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyPojo tp = mapper.readValue(payloadJson, MyPojo.class);
if http://pojo.sodhanalibrary.com/ ceases to exist in the future, just internet search "online json to pojo" and you'll probably find something.

Assigning list of HashMap to another list of HashMap as method return value

I am trying to assign a method's return value to a List of HashMaps.
Method returning List
public List<HashMap<String, String>> getDetails() {
List<HashMap<String, String>> info = new ArrayList<HashMap<String, String>>();
HashMap<String, String> components = new HashMap<String, String>();
//Fetched some result from DataBase in ResultSet (assume i have fetched three rows).
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
components.put("id", rs.getString("id"));
components.put("columnA", rs.getString("columnA"));
components.put("columnB", rs.getString("columnB"));
components.put("columnC", rs.getString("columnC"));
components.put("columnD", rs.getString("columnD"));
info.add(components);
}
return info;
}
Calling Method
public void dispDetails(){
List<HashMap<String, String>> info = new ArrayList<HashMap<String, String>>();
details = getDetails();
for(int i=0;i<3;i++){
System.out.println(details.get(i).get("id"));
System.out.println(details.get(i).get("columnA"));
System.out.println(details.get(i).get("columnB"));
System.out.println(details.get(i).get("columnC"));
System.out.println(details.get(i).get("columnD"));
}
}
But somehow all the values in the calling methods list(i.e dispDetails) are same.
Is there any way to assign the list.

how can I query for releases / iterations via rally c# api?

I am trying to query on both Release and Iteration so I can fill out a drop down list with these various values. I'm not quite sure how to do this, however. What are the members of the object that come back via the query if we are able to do this? (Name, FormattedID, CreationDate, etc). Do we just create a new request of type "Release" and "Iteration" ?
Thanks!
Here is a code that queries on releases based on a project reference. If this project is not in a default workspace of the user that runs the code we either need to hardcode the workspace reference or get it from the project.
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "TopSecret1984", "https://rally1.rallydev.com", "1.40");
var projectRef = "/project/22222222"; //use your project OID
DynamicJsonObject itemWorkspace = restApi.GetByReference(projectRef, "Workspace");
var workspaceRef = itemWorkspace["Workspace"]["_ref"];
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
Request request = new Request("Release");
request.ProjectScopeDown = false;
request.ProjectScopeUp = false;
request.Workspace = workspaceRef;
request.Fetch = new List<string>()
{
"Name"
};
// request.Query = new Query("Project.ObjectID", Query.Operator.Equals, "22222222"); //also works
request.Query = new Query("Project", Query.Operator.Equals, projectRef);
QueryResult queryResult = restApi.Query(request);
foreach (var r in queryResult.Results)
{
Console.WriteLine("Name: " + r["Name"]);
}
}
catch
{
Console.WriteLine("problem!");
}
}
}
}

Setting language in a fakeApplication() for Play! 2.0.2

running(fakeApplication(), new Runnable() {
public void run() {
Content html = views.html.index.render(loginForm);
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(contentAsString(html)).contains("log in");
}
});
We use this code to test that a view is rendered properly, but the problem is that the text in the view doesn't use the Messages.en-file we have specified for our actual application (so it renderes login.login instead of "log in" for instance).
Is there a way to configure the fakeapplication to use a specific langauge (and then have it look for the appropriate messages-file)?
We tried this to no avail:
Map<String, String> config = new HashMap<String, String>();
config.put("application.langs", "en");
FakeApplication fakeApp = new FakeApplication(additionalConfiguration = config);
Try this:
Map<String, String> config = new HashMap<String, String>();
config.put("application.langs", "en");
FakeApplication fakeApp = new FakeApplication(new java.io.File("conf/"), Helpers.class.getClassLoader(), config, , new ArrayList<String>())`;