How to get the Chinese name of a security in blpapi? - java

I have a BDP function that looks like this.
BDP("Glen Ln Equity","NAME_CHINESE_SIMPLIFIED")
It is to update the Chinese name of a security.
I have to translate it to Java blpapi but I am not sure how.
Since this is a BDP function, I think I should use Reference Data Request but you can only specify the ticker and field mnemonic when creating a Reference Data Request. I also know I can use override but to use an override, based on my understanding, I will need a fieldID so that I can set that fieldID's value to be "NAME_CHINESE_SIMPLIFIED".
However, I am not sure what fieldID to use.
What fieldID should I use for the override?
Also, where can I find a list of fieldIDs that can set for overrides?

It should work fine with a reference data request - you don't need to override anything here:
Element security = request.getElement("securities");
security.appendValue("GLEN LN Equity");
Element field = request.getElement("fields");
field.appendValue("NAME_CHINESE_SIMPLIFIED ");

Related

Unable to get a variable value in drools and use it to set in another field

drl file :
rule "pendingMsgSizeModified"
when
$tibcoEMSObj : TibcoEMSData(deliveredMsgCnt.contains("MB") && pendingMsgSize \> 100)
eval (!($tibcoEMSObj.typeOfAlert != null))
then
$tibcoEMSObj.setSendEmail(true);
$tibcoEMSObj.setTypeOfAlert($tibcoEMSobj.getTypeOfAlert()+"pendingMsgSize###");
update($tibcoEMSObj)
end
It gives error at this location : $tibcoEMSobj.getTypeOfAlert()
Error : \[Error: unable to resolve method using strict-mode: org.drools.core.spi.KnowledgeHelper.$tibcoEMSobj()\]
\[Near : {... SObj.setTypeOfAlert($tibcoEMSobj.getTypeOfAlert()+ ....}\]
I am expecting to use the getter method to get it and concatenate the string to set in another variable and save/update it
Your syntax is all over the place. And without actually seeing your model, it's hard to tell what you're even trying to do.
But based on what you said:
I am expecting to use the getter method to get it and concatenate the string to set in another variable and save/update it
And the code you did provide, I think this is what you're trying to do:
rule "pendingMsgSizeModified"
when
$tibcoEMSObj : TibcoEMSData(
deliveredMsgCnt.contains("MB"),
pendingMsgSize > 100,
$alertType: typeOfAlert != null
)
then
String newAlert = $alertType + "pendingMsgSize###";
modify($tibcoEMSObj) {
setSendEmail(true)
setTypeOfAlert(newAlert)
}
end
I presumed that your eval was either typo'd or just plain wrong since it was checking that the value was actually null. Don't use eval unless you have absolutely no other choice. (And I've never actually run into a situation where there was no other choice.)
I also presumed that the alert type will not change. I don't know what your sendEmail method does, or if it has side effects; if it does have side effects that change the typeOfAlert, then you'll of course need to call getTypeOfAlert() after calling setSendEmail.

How to replace a query string in an Apache Velocity template?

In my web application I'm trying to prevent users from inserting JavaScript in the freeText parameter when they're running a search.
To do this, I've written code in the header Velocity file to check whether the query string contains a parameter called freeText, and if so, use the replace method to replace the characters within the parameter value. However, when you load the page, it still displays the original query string - I'm unsure on how to replace the original query string with my new one which has the replaced characters.
This is my code:
#set($freeTextParameter = "$request.getParameter('freeText')")
freeTextParameter: $freeTextParameter
#if($freeTextParameter)
##Do the replacement:
#set($replacedQueryString = "$freeTextParameter.replace('confirm','replaced')")
replacedQueryString after doing the replace: $replacedQueryString
The query string now: $request.getQueryString()
The freeText parameter now: $request.getParameter('freeText')
#end
In the code above, the replacedQueryString variable has changed as expected (ie the replacement has been carried out as expected), but the $request.getQueryString() and $request.getParameter('freeText') are still the same as before, as if the replacement had never happened.
Seeing as there is a request.getParameter method which works fine for getting the parameters, I assumed there would be a request.setParameter method to do the same thing in reverse, but there isn't.
The Java String is an immutable object, which means that the replace() method will return an altered string, without changing the original one.
Since the parameters map given by the HttpServletRequest object cannot be modified, this approach doesn't work well if your templates rely on $request.getParameter('freeText').
Instead, if you rely on VelocityTools, then you can rather rely on $params.freeText in your templates. Then, you can tune your WEB-INF/tools.xml file to make this parameters map alterable:
<?xml version="1.0">
<tools>
<toolbox scope="request">
<tool key="params" readOnly="false"/>
...
</toolbox>
...
</tools>
(Version 2.0+ of the tools is required).
Then, in your header, you can do:
#set($params.freeText = params.freeText.replace('confirm','replaced'))
I managed to fix the issue myself - it turned out that there was another file (which gets called on every page) in which the $!request.getParameter('freeText')" variable is used. I have updated that file so that it uses the new $!replacedQueryString variable (ie the one with the JavaScript stripped out) instead of the existing "$!request.getParameter('freeText')" variable. This now prevents the JavaScript from being executed on every page.
So, this is the final working code in the header Velocity file:
#set($freeTextParameter = "$!m.request.httpRequest.getParameter('freeText')")
#if($freeTextParameter)
#set($replacedQueryString = "$freeTextParameter.replace('confirm','').replace('<','').replace('>','').replace('(','').replace(')','').replace(';','').replace('/','').replace('\"','').replace('&','').replace('+','').replace('script','').replace('prompt','').replace('*','').replace('.','')")
#end

how to list all the indices' name of elasticsearch using java?

In my elasticsearch I want to get all the indices' name of the cluster. How can I do using java?
I search the internet but there's no much useful information.
You can definitely do it with the following simple Java code:
List<IndexMetaData> indices = client.admin().cluster()
.prepareState().get().getState()
.getMetaData().getIndices();
The list you obtain contains the details on all the indices available in your ES cluster.
You can use:
client.admin().indices().prepareGetIndex().setFeatures().get().getIndices();
Use setFeatures() without parameter to just get index name. Otherwise, other data, such as MAPPINGS and SETTINGS of index, will also be returned by default.
Thanks for #Val's answer. According to your method, I use it in my projects, the code is:
ClusterStateResponse response = transportClient.admin().cluster() .prepareState()
.execute().actionGet();
String[] indices=response.getState().getMetaData().getConcreteAllIndices();
This method can put all the indices name into a String array. The method works.
there's another method I think but not tried:
ImmutableOpenMap<String, MappingMetaData> mappings = node.client().admin().cluster()
.prepareState().execute().actionGet().getState().‌getMetaData().getIndices().
then, we can get the keys of mappings to get all the indices.
Thanks again!

Passing nullable parameters to a Page via PageParameters in Wicket 6

I need to pass a parameter to my page and I can't find a way to pass parameters that might be null.
If I do:
PageParameters pageParameters = new PageParameters ();
pageParameters.add ("key", null);
This will result in an exception
java.lang.IllegalArgumentException: Argument 'value' may not be null.
at org.apache.wicket.util.lang.Args.notNull(Args.java:41)
If I use Google Guava's Optional, I can't find any way to cast the object even if the the Optional object is not holding a null ie not equals to Optional.absent() :
In my landing page's constructor I do
StringValue sv = parameters.get ("key");
sv.to ( Optional.of (MyEnum.SOME_ENUM_CONSTANT).getClass () );
and when I run it I get this error:
org.apache.wicket.util.string.StringValueConversionException: Cannot
convert 'Optional.of(SOME_ENUM_CONSTANT)'to type class
com.google.common.base.Present.
Am I doing something wrong?
Is there any other way to pass a possibly null object in wicket 6?
I noticed in wicket 1.4 they have PageParameters.NULL which seems to have dissapeared in wicket 6.
Thank you
This might be too simple, but what's wrong with
Object value = ?
if (value != null) {
pageParameters.add ("key", value);
}
and
StringValue sv = pageParameters.get("key");
if (!sv.isNull()) {
// process string value
}
All page parameters in wicket will be treated as Strings eventually. The idea is that a page parameter will be on the URL of the request.
From the javadoc:
Suppose we mounted a page on /user and the following url was accessed /user/profile/bob?action=view&redirect=false. In this example profile and bob are indexed parameters with respective indexes 0 and 1. action and redirect are named parameters.
If you add something like x=y&x, the parameter x will appear twice, once with the String y and another with the empty string.
Depending on what you are trying to accomplish I would suggest to either
Don't pass the parameter at all when there is a null value required and use the isNull or toOptional methods.
Use indexed parameters and test for presence of a certain word

Simple way to use parameterised UI messages in Wicket?

Wicket has a flexible internationalisation system that supports parameterising UI messages in many ways. There are examples e.g. in StringResourceModel javadocs, such as this:
WeatherStation ws = new WeatherStation();
add(new Label("weatherMessage", new StringResourceModel(
"weather.${currentStatus}", this, new Model<String>(ws)));
But I want something really simple, and couldn't find a good example of that.
Consider this kind of UI message in a .properties file:
msg=Value is {0}
Specifically, I wouldn't want to create a model object (with getters for the values to be replaced; like WeatherStation in the above example) only for this purpose. That's just overkill if I already have the values in local variables, and there is otherwise no need for such object.
Here's a stupid "brute force" way to replace the {0} with the right value:
String value = ... // contains the dynamic value to use
add(new Label("message", getString("msg").replaceAll("\\{0\\}", value)));
Is there a clean, more Wicket-y way to do this (that isn't awfully much longer than the above)?
Take a look at Example 4 in the StringResourceModel javadoc - you can pass a null model and explicit parameters:
add(new Label("message",
new StringResourceModel(
"msg", this, null, value)));
msg=Value is {0}
I think the most consistent WICKETY way could be accomplished by improving Jonik's answer with MessageFormat:
.properties:
msg=Saving record {0} with value {1}
.java:
add(new Label("label", MessageFormat.format(getString("msg"),obj1,obj2)));
//or
info(MessageFormat.format(getString("msg"),obj1,obj2));
Why I like it:
Clean, simple solution
Uses plain Java and nothing else
You can replace as many values as you want
Work with labels, info(), validation, etc.
It's not completely wickety but it is consistent with wicket so you may reuse these properties with StringResourceModel.
Notes:
if you want to use Models you simply need to create a simple model that override toString function of the model like this:
abstract class MyModel extends AbstractReadOnlyModel{
#Override
public String toString()
{
if(getObject()==null)return "";
return getObject().toString();
}
}
and pass it as MessageFormat argument.
I don't know why Wicket does not support Model in feedback message. but if it was supported there was no reason to use these solutions and you could use StringResourceModel everywhere.
There's a way, which although still involves creating a model, doesn't requires a bean with a getter.
given this message in a properties file:
msg=${} persons
Here's how to replace the placeholder with a value, be it a local variable, a field or a literal:
add(new Label("label", new StringResourceModel("msg", new Model<Serializable>(5))));
When faced with something like described in the question, I would now use:
.properties:
msg=Saving record %s with value %d
Java:
add(new Label("label", String.format(getString("msg"), record, value)));
Why I like it:
Clean, simple solution
Uses plain Java and nothing else
You can replace as many values as you want (unlike with the ${} trick). Edit: well, if you actually need to support many languages where the replaced values might be in different order, String.format() is no good. Instead, using MessageFormat is a similar approach that properly supports this.
Disclaimer: this is "too obvious", but it's simpler than the other solutions (and definitely nicer than my original replaceAll() hack). I originally sought for a "Wicket-y" way, while this kinda bypasses Wicket—then again, who cares? :-)
In case you have a Model in your Component which holds an object with values you want to access from your placeholders as substitutions, you can write:
new StringResourceModel("salutation.text", getModel());
Let's imagine getModel()'s return type is IModel<User> and User contains fields like firstName and lastName. In this case you can easily access firstName and lastName fields inside your property string:
salutation.text=Hej ${firstName} ${lastName}, have a nice day!
Further information you can find here: https://ci.apache.org/projects/wicket/apidocs/8.x/org/apache/wicket/model/StringResourceModel.html#StringResourceModel-java.lang.String-org.apache.wicket.model.IModel-
Creating a Model for your Label really is The Wicket Way. That said, you can make it easy on yourself with the occasional utility function. Here's one I use:
/**
* Creates a resource-based label with fixed arguments that will never change. Arguments are wrapped inside of a
* ConvertingModel to provide for automatic conversion and translation, if applicable.
*
* #param The component id
* #param resourceKey The StringResourceModel resource key to use
* #param component The component from which the resourceKey should be resolved
* #param args The values to use for StringResourceModel property substitutions ({0}, {1}, ...).
* #return the new static label
*/
public static Label staticResourceLabel(String id, String resourceKey, Component component, Serializable... args) {
#SuppressWarnings("unchecked")
ConvertingModel<Serializable>[] models = new ConvertingModel[args.length];
for ( int i = 0; i < args.length; i++ ) {
models[i] = new ConvertingModel<Serializable>( new Model<Serializable>( args[i] ), component );
}
return new CustomLabel( id, new StringResourceModel( resourceKey, component, null, models ) );
}
Details I'm glossing over here are:
I've created my own ConvertingModel which will automatically convert objects to their String representation based on the IConverters available to the given component
I've created my own CustomLabel that applies custom label text post-processing (as detailed in this answer)
With a custom IConverter for, say, a Temperature object, you could have something like:
Properties key:
temperature=The current temperature is ${0}.
Page.java code:
// Simpler version of method where wicket:id and resourceKey are the same
add( staticResourceLabel( "temperature", new Temperature(5, CELSIUS) ) );
Page.html:
<span wicket:id='temperature'>The current temperature is 5 degrees Celsius.</span>
The downside to this approach is that you no longer have direct access to the Label class, you can't subclass it to override isVisible() or things like that. But for my purposes it works 99% of the time.

Categories

Resources