How to query metadata of an OData action? - apache

I want to query metadata of an OData action in order to find out, which parameters are expected and how they are named.
I am aware, that I can figure this out by typing link-to-service-root.com/service.svc/$metadata. However, in this case I have to dig through the complete metadata output.
Instead I am looking for an elegant way to do this. Maybe there exists a query link-to-service-root.com/service.svc/$metadata/Action('Namespace.NameOfAction') (inspired by blog post on queryable odata metadata).
Thanks for your input!

You can get the Action (or Actions) from the EDM and then play with parameters. Let me know if this helps.
String serviceRoot = "http://services.odata.org/V4/TripPinServiceRW/";
EdmMetadataRequest request = ODataClientFactory.getClient().getRetrieveRequestFactory().getMetadataRequest(serviceRoot);
ODataRetrieveResponse<Edm> response = request.execute();
Edm edm = response.getBody();
List<EdmAction> edmActions = edm.getSchemas().get(0).getActions(); //get the first schema
for (EdmAction action : edmActions) {
System.out.println("Action name: " + action.getName());
List<String> actionParamNames = action.getParameterNames();
System.out.println("Parameters: ");
for (String actionParamName : actionParamNames) {
EdmParameter param = action.getParameter(actionParamName);
System.out.println(param.getName() + " (" + param.getType().getName() + ")");
//getMaxLength //getPrecision //isNullable //isCollection //etc.
}
System.out.println("---------------------");
}

Related

DBArrayList to List<Map> Conversion after Query

Currently, I have a SQL query that returns information to me in a DBArrayList.
It returns data in this format : [{id=2kjhjlkerjlkdsf324523}]
For the next step, I need it to be in a List<Map> format without the id: [2kjhjlkerjlkdsf324523]
The Datatypes being used are DBArrayList, and List.
If it helps any, the next step is a function to collect the list and then to replace all single quotes if any [SQL-Injection prevention]. Using:
listMap = listMap.collect() { "'" + Util.removeSingleQuotes(it) + "'" }
public static String removeSingleQuotes(s) {
return s ? s.replaceAll(/'"/, '') : s
}
I spent this morning working on it, and I found out that I needed to actually collect the DBArrayList like this:
listMap = dbArrayList.collect { it.getAt('id')}
If you're in a bind like I was and restrained to a specific schema this might help, but #ou_ryperd has the correct answer!
While using a DBArrayList is not wrong, Groovy's idiom is to use the db result as a collection. I would suggest you use it that way directly from the db:
Map myMap = [:]
dbhandle.eachRow("select fieldSomeID, fieldSomeVal from yourTable;") { row ->
map[row.fieldSomeID] = row.fieldSomeVal.replaceAll(/'"/, '')
}

How to get Alfresco custom content model property information?

Is there any way to programmatically understand what properties there are for a custom model in Alfresco?
For example, data dictionary in oracle helps you to find what tables are defined by which column names and column data types.
My goal is a sample code in java which extracts all custom defined content models, their attributes, their attributes data types, etc. For example my sample code should return to me that there is a custom content Model which has an integer attribute with name 'No' and a string attribute with name 'Description'. I know this is possible with DictionaryComponent, But I don't know how should I use it.
Take a look at org.alfresco.service.cmr.dictionary.DictionaryService.
will your Java-code running in-context with alfresco (as part of the /alfresco webapp) or outside?
If your running in-context, then Alfreso Java Foundation API is your choice where DictionaryService is part of. just inject the bean into your java code.
If your code is running outside of alfresco, then Alfresco REST API or CMIS is your choice.
If you're still lost, then train yourself first. Jeff wrote some good articles http://ecmarchitect.com/alfresco-developer-series & also a book.
Also a good starting point - Alfresco Developer Docs: http://docs.alfresco.com/4.2/topic/com.alfresco.enterprise.doc/concepts/dev-for-developers.html
thanks a lot of alfresian responses, My code sample is something like below:
I found the sample code from : this URL
public void GetAllAvailableDataTypes() throws IOException
{
Session session = getSession();
boolean includePropertyDefintions = true;
for (Tree t : session.getTypeDescendants(
null, // start at the top of the tree
-1, // infinite depth recursion
includePropertyDefintions // include prop defs
)) {
printTypes(t, "");
}
}
public void printTypes(Tree tree, String tab) {
ObjectType objType = (ObjectType) tree.getItem();
String type = objType.getId();
if(true)//type.endsWith("hstcase"))
{
System.out.println(tab + "TYPE:" + objType.getDisplayName() +
" (" + objType.getDescription() + ")");
//Print some of the common attributes for this type
System.out.print(tab + " Id:" + "-----"+ objType.getId() + "-----");
System.out.print(" Fileable:" + objType.isFileable());
System.out.print(" Queryable:" + objType.isQueryable());
if (objType instanceof DocumentType) {
System.out.print(" [DOC Attrs->] Versionable:" +
((DocumentType)objType).isVersionable());
System.out.println(" Content:" +
((DocumentType)objType).getContentStreamAllowed());
Map<String, org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition<?>> props = objType.getPropertyDefinitions();
Set<String> keys = props.keySet();
Collection<org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition<?>> porpsAsCollection = props.values();
for(org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition<?> p: porpsAsCollection)
{
//System.out.println(p.getDescription());
PropertyType pt = p.getPropertyType();
System.out.println("Display Name: "+ p.getDisplayName());
System.out.println("Local Name: "+ p.getLocalName());
System.out.println("Attribute Type: "+ pt.value());
}
}
System.out.println(""); // end the line
}
List<Tree> childs = tree.getChildren();
for (Tree t : childs) {
// there are more - call self for next level
printTypes(t, tab + " ");
}
}

How can Jdbc template be used for UPDATE query with IN clause?

I've gone through various forums to handle the IN clause using spring's namedParamJdbcTemplate but i still do not get the stuff I'm exactly looking for.
Below is my issue:
I've the following method:
public void updateBatchTableForStatus(List<Integer> reportShellIds, String scheduleType) {
Map<String,List<Integer>> shellIds = Collections.singletonMap("reportShellIds", reportShellIds);
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("reportShellIds", shellIds, Types.NUMERIC)
parameters.addValue("eventType", scheduleType, Types.VARCHAR);
this.namedParamJdbcTemplate.update(GET_EVENT_METADATA_INFO, parameters);
}
The query refered in above method is as defined below:
public static final String SQL_UPDATE_BATCH_LOOKUP_TABLE_FOR_STATUS_BY_BATCH_IDS = "" +
"UPDATE " +
TABLE_BATCH_REF + " BLK " +
"SET " +
"BLK.EXECUTION_STATUS_CODE = :eventType " +
"WHERE " +
"BLK.BATCH_ID in(:reportShellIds) ";
Datatype for BATCH_ID column is Number(24,0) and for the EXECUTION_STATUS_CODE column Varchar.
I'm using Oracle db.
However, the above method throws a SQL exception.
Can someone pls tell me where I'm wrong and what is the fix for it ?
Many thanks in advance.
Best Regards
LB
You are binding reportShellIds to a Map, but it needs to be a List for Spring to bind it correctly. Perhaps you meant shellIds.values() or the variable reportShellIds?
You can use another method with simple Map<String,Object> and place the array as is into the parameter map
public int update(String sql, java.util.Map<java.lang.String,?> paramMap)

nHibernate set referenced property by id

I have the following method which is called from Ajax:
[Authorize]
[ValidateInput(false)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JsonNetResult CreateOrUpdateTimeRecord(TimeRecord tr)
{
TimeRecord trLocal;
if (tr.Id == -1 || tr.Id == 0)
{
trLocal = new TimeRecord
{
Description = tr.Description,
StartTime = tr.StartTime,
EndTime = tr.EndTime,
User =new myTimeMvc.Models.NHibernate.Models.User {Id = tr.User.Id},// _userRepo.Get(tr.User.Id),
Hdt = new Hdt {Id = tr.Hdt.Id}//_hdtRepo.Get(tr.Hdt.Id)
};
_timeRepo.Insert(trLocal);
}
else
{
trLocal = _timeRepo.Get(tr.Id);
trLocal.Description = tr.Description;
trLocal.StartTime = tr.StartTime;
trLocal.EndTime = tr.EndTime;
_timeRepo.Update(trLocal);
}
...
}
As you can see my TimeRecord has a reference to User and Hdt. Now I started to work with NHibernate Profiler which complains when I resolve my properties by loading them from their coresponding repositories. Which is clear to me since I actually don't need to query the database for that since I have the ID's for this objects.
User = _userRepo.Get(tr.User.Id),
Hdt = _hdtRepo.Get(tr.Hdt.Id)
But I'm not 100% sure if I can use this instead:
User =new myTimeMvc.Models.NHibernate.Models.User {Id = tr.User.Id},,
Hdt = new Hdt {Id = tr.Hdt.Id}
I guess NHibernate lazy proxies work the same way since they only contain just the ID of the related object and load the rest when it is needed. Do I have to attach this "new" oject anyway to my session?
Can someone tell me what is the correct way to do this?
Cheers,
Stefan
There are a few ways how to achieve that. One of them could be using the Load() method. Check Ayendes post: NHibernate – The difference between Get, Load and querying by id, an extract:
Load will never return null. It will always return an entity or throw an exception. Because that is the contract that we have we it, it is permissible for Load to not hit the database when you call it, it is free to return a proxy instead.
Other words, we can do something like this
User = _userRepo.Load(tr.User.Id),
Hdt = _hdtRepo.Load(tr.Hdt.Id)
Where the Load would be encapsulating the session.Load()

Does Dapper support the like operator?

Using Dapper-dot-net...
The following yields no results in the data object:
var data = conn.Query(#"
select top 25
Term as Label,
Type,
ID
from SearchTerms
WHERE Term like '%#T%'",
new { T = (string)term });
However, when I just use a regular String Format like:
string QueryString = String.Format("select top 25 Term as Label, Type, ID from SearchTerms WHERE Term like '%{0}%'", term);
var data = conn.Query(QueryString);
I get 25 rows back in the collection. Is Dapper not correctly parsing the end of the parameter #T?
Try:
term = "whateverterm";
var encodeForLike = term => term.Replace("[", "[[]").Replace("%", "[%]");
string term = "%" + encodeForLike(term) + "%";
var data = conn.Query(#"
select top 25
Term as Label,
Type,
ID
from SearchTerms
WHERE Term like #term",
new { term });
There is nothing special about like operators, you never want your params inside string literals, they will not work, instead they will be interpreted as a string.
note
The hard-coded example in your second snippet is strongly discouraged, besides being a huge problem with sql injection, it can cause dapper to leak.
caveat
Any like match that is leading with a wildcard is not SARGable, which means it is slow and will require an index scan.
Yes it does. This simple solution has worked for me everytime:
db.Query<Remitente>("SELECT *
FROM Remitentes
WHERE Nombre LIKE #n", new { n = "%" + nombre + "%" })
.ToList();
Best way to use this to add concat function in query as it save in sql injecting as well, but concat function is only support above than sql 2012
string query = "SELECT * from country WHERE Name LIKE CONCAT('%',#name,'%');"
var results = connection.query<country>(query, new {name});
The answer from Sam wasn't working for me so after some testing I came up with using the SQLite CONCAT equivalent which seems to work:
string sql = "SELECT * FROM myTable WHERE Name LIKE '%' || #NAME || '%'";
var data = IEnumerable data = conn.Query(sql, new { NAME = Name });
Just to digress on Sam's answer, here is how I created two helper methods to make searches a bit easier using the LIKE operator.
First, creating a method for generating a parameterized query, this method uses dynamic: , but creating a strongly typed generic method should be more desired in many cases where you want static typing instead of dynamic.
public static dynamic ParameterizedQuery(this IDbConnection connection, string sql, Dictionary<string, object> parametersDictionary)
{
if (string.IsNullOrEmpty(sql))
{
return null;
}
string missingParameters = string.Empty;
foreach (var item in parametersDictionary)
{
if (!sql.Contains(item.Key))
{
missingParameters += $"Missing parameter: {item.Key}";
}
}
if (!string.IsNullOrEmpty(missingParameters))
{
throw new ArgumentException($"Parameterized query failed. {missingParameters}");
}
var parameters = new DynamicParameters(parametersDictionary);
return connection.Query(sql, parameters);
}
Then adding a method to create a Like search term that will work with Dapper.
public static string Like(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm))
{
return null;
}
Func<string, string> encodeForLike = searchTerm => searchTerm.Replace("[", "[[]").Replace("%", "[%]");
return $"%{encodeForLike(searchTerm)}%";
}
Example usage:
var sql = $"select * from products where ProductName like #ProdName";
var herringsInNorthwindDb = connection.ParameterizedQuery(sql, new Dictionary<string, object> { { "#ProdName", Like("sild") } });
foreach (var herring in herringsInNorthwindDb)
{
Console.WriteLine($"{herring.ProductName}");
}
And we get our sample data from Northwind DB:
I like this approach, since we get helper extension methods to do repetitive work.
My solution simple to this problem :
parameter.Add("#nomeCliente", dfNomeCliPesquisa.Text.ToUpper());
query = "SELECT * FROM cadastrocliente WHERE upper(nome) LIKE " + "'%" + dfNomeCliPesquisa.Text.ToUpper() + "%'";