I want to store a Riak Pojo object with links in the database using the java. Eventhough the field type is Collection <RiakLink>, it keep throwing the same exception "riak links field must be Collection <RiakLink> ".
Code:
class Pojo{
public String name;
#RiakKey
public String key;
#RiakLinks
#JsonIgnore
public Collection<RiakLink> collection = new ArrayList<RiakLink>();
}
public class Riak2 {
public static void main(String[] args) throws RiakException {
IRiakClient client = RiakFactory.httpClient();
Pojo p = new Pojo();
p.name = "Pojo";
p.key = "First";
p.collection.add(new RiakLink("list","Second","next"));
client.fetchBucket("list").execute().store(p);
}
}
Exception : Exception in thread "main" java.lang.RuntimeException: java.lang.IllegalArgumentException: riak links field must
be Collection <RiakLink> at com.basho.riak.client.convert.reflect.AnnotationCache.get(AnnotationCache.java:56)
Please give me a help
Thanks
I've tested this in both the current 1.1.3 and 1.4.2 versions of the client and can not reproduce this issue.
In addition, there's actually a unit test that ensures this works.
Looking though the history for AnnotationCache, I can't find where there was ever a bug regarding this since it was created about two years ago so that rules out you using an old version of the client that has a bug.
Given that, I would suggest rebuilding your project / rechecking that the code you list in your Q is what is actually being used. As shown, there's no problem with it.
Related
I'm very new to the FHIR standard and I could use some help figuring out how to evaluate a ruleExpression against an object.
Here is my object:
#ResourceDef(name = "TestObj", profile = "http://hl7.org/fhir/StructureDefinition/TestObj")
#Data
public class TestObj extends DomainResource {
private static final long serialVersionUID = 1L;
#Child(name = "numMarbles")
#Extension(url = "http://hl7.org/fhir/CustomExtension/numMarbles", definedLocally = true, isModifier = false)
#Description(shortDefinition = "The number of marbles I have in my pocket")
private IntegerType numMarbles;
}
I'm trying to figure out how to run a rule evaluation on it. For example:
String ruleExp = "%numMarbles > 3"
In order to try options.. I've setup the following integration test:
#Test
void doRuleEval() throws Exception {
TestObj t = new TestObj();
t.setNumMarbles(4);
String ruleExp = "%numMarbles > '3'";
FhirPathR4 path = new FhirPathR4(fhirContext);
// ?????
Object something = path.evaluate(t, ruleExp, null);
// Line above always fails: "unknown fixed constant %numMarbles"
log.info("something: " + something.toString());
}
I've scoured the FHIR documentation and can't find java examples for how to evaluate dynamic rules against FHIR models. In the Javascript library we used the "compile" method but I can't find the equivalent Java method.
I feel like I'm missing something fundamental here.
The "evaluate" method is not documented - it takes in an "IBase" object which is any FHIR object from what I can tell, and returns some sort of list... who knows.
The FhirPathR4 object also contains a "parse" method that returns nothing and is also un-documented.
Thanks for any help or tips to point me in the right direction for evaluating a "ruleExpression" against an object's fields.
I would go onto the HAPI FHIR Google group as ask about the evaluate method there.
https://groups.google.com/g/hapi-fhir?pli=1
I am trying to make my own SonarQube rule, the objective of the rule is to check that I am not using the contains method on a collection of a specific object. Example with Integer Object :
List<Integer> a = new ArrayList<>();
a.contains(1); // Noncompliant
To do that I am trying to get the ParametrizedTypeJavaType. Then I will be able to test if it is an Integer or not ...
#Override
public void visitNode(Tree tree) {
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
ExpressionTree expressionTree = ((MethodInvocationTree) tree).methodSelect();
if(expressionTree.is(Kind.MEMBER_SELECT)){
MemberSelectExpressionTree memberSelectExpressionTree = (MemberSelectExpressionTree) expressionTree;
Type type = memberSelectExpressionTree.expression().symbolType();
ParametrizedTypeJavaType parametrizedTypeJavaType = (ParametrizedTypeJavaType) type;
// SOME CODE Test if it is an integer or not ...
reportIssue(tree,"REPORT !");
}
}
#Override
public List<Kind> nodesToVisit() {
List<Kind> kinds = new ArrayList<>();
kinds.add(Kind.METHOD_INVOCATION);
return kinds;
}
}
It seems to work well during jUnit test but when i launched sonnar-scanner on my test project I get the following error :
Caused by: java.lang.ClassCastException: org.sonar.java.resolve.ParametrizedTypeJavaType cannot be cast to org.sonar.java.resolve.ParametrizedTypeJavaType
at org.sonar.samples.java.checks.CollectionCheck.visitNode(CollectionCheck.java:38)
I have done some research and I came across this question, that looks to be my problem :
Sonarqube error java.lang.ClassCastException: org.sonar.java.resolve.SemanticModel cannot be cast to org.sonar.java.resolve.SemanticModel
I came also across this rule which looks very similar to my rule and uses ParametrizedTypeJavaType.
https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/main/java/org/sonar/java/checks/CollectionInappropriateCallsCheck.java
So I am totally confused. What is the good approach to deal with my problem ?
SonarQube version : 6.3.1
Thanks for your help.
ParametrizedTypeJavaType is not part of the java api for custom rule. And as of today semantic API does not allow you to access to generics information : This is planned but not scheduled : https://jira.sonarsource.com/browse/SONARJAVA-1871
You are better off relying on the existing rule for what you want to achieve : https://sonarqube.com/coding_rules#rule_key=squid%3AS2175
If this rule does not work correctly for you can you explain why ?
I'm learning about Sets and Maps in the Introduction to Java Programming book by Daniel Liang. My professor has assigned a problem in the back of the chapter that asks me to create a program that:
Queries the user for input on name
Queries the user for gender
Using these two criteria, and this/these website(s): http://cs.armstrong.edu/liang/data/babynamesranking2001.txt
... http://cs.armstrong.edu/liang/data/babynamesranking2010.txt
I have to be able to get the ranking.
I'm supposed to get this information into an array of 10 maps.
Each map corresponds with a .txt file/year. This is where I'm having problems with. How do I do this?
The (Int) rank of the student is the value of the map, and the key is the name (String) of the baby.
The way I was thinking was to create an array of maps or maybe a list of them. So like:
List<Map<Int, String>> or <Map<Int, String>[] myArray;
Yet even after that the issue of how I get all of this information from the .txt file to my maps is a hard one for me.
This is what I've come up so far. I can't say I'm happy with it. It doesn't even work when I try to start reading information is because I haven't specified the size of my array.
public class BabyNamesAndPopularity
{
public static void main (String[] args) throws IOException
{
Map<Integer, String>[] arrayOfMaps;
String myURL = "cs.armstrong.edu/liang/data/babynamesranking2001.txt";
java.net.URL url = new java.net.URL(myURL);
Scanner urlInput = new Scanner (url.openStream());
while(urlInput.hasNext())
{
...
}
}
}
Would it be viable to make a set OF MAPS? I was kind of thinking it would be better to make a set OF maps because of the fact that sets expand as needed (according to the load factor). I just need some general guidance. Unfortunately the CS program at my university (Francis Marion University in Florence, SC) is VERY small and we don't have any tutors for this stuff.
This answer rather vague, because of broad nature of question, and it may be more suitable for
programmers SE site. Still, you may find these two points worth something.
Instead of thinking in terms of 'raw' compound collections, such as lists of maps of sets or such, try to invent set of domain types, which would reflect your problem domain, and, as the next step, implement these types using suitable Java collections or arrays.
Unit-testing and incremental refinement. Instead of immediately starting with access to remote data (via java.net.URL), start with static source of data. Idea here is to have 'reliable' and easily accessible input data hand, which would allow you to write unit tests easily and w/o access to network or even to file system, using set of domain types from 1st point, above. As you write unit tests you can invent necessary domain types/methods names in unit tests at first, then implement these types/methods, then make unit tests pass.
For example, you may start by writing following unit test (I assume you know how to organize your Java project in your IDE, so unit test(s) can be run properly):
public class SingleFileProcessingTest {
private static String[] fileRawData;
#BeforeClass
public static void fillRawData() {
fileRawData = new String[2];
// values are from my head, resembling format from links you've posted
fileRawData[0] = "Jacob\t20000\tEmily\t19999";
fileRawData[1] = "Michael\t18000\tMadison\t17000";
}
#Test
public void test() {
Rankings rankings = new Rankings();
rankings.process(fileRawData);
assertEquals("Jacob", rankings.getTop().getName());
assertEquals("Madison", rankings.getScorerOfPosition(4).getName());
assertEquals(18000, rankings.getScoreOf("Michael"));
assertEquals(4, rankings.getSize());
}
}
Of course, this won't even compile -- you need to type in code of Rankings class, code of class returned by getTop() or getScorerOfPosition(int) and so on. After you made this compile, you'll need to make test pass. But you get main idea here -- domain types and incremental refinement. And easily verifiable code w/o dependencies on file system or network. Just plain old java objects (POJOs). Code for working with external data sources can be added later on, after you get your POJOs right and make tests, which cover most parts of your use cases, pass.
UPDATE Actually, I've mixed up levels of abstraction in code above: proper Rankings class should not process raw data, this is better to be done in separate class, say, RankingsDataParser. With that, unit test, renamed to RankingsProcessingTest, will be:
public class RankingsProcessingTest {
#Test
public void test() {
Rankings rankings = new Rankings();
rankings.addScorer(new Scorer("Jacob", 20000));
rankings.addScorer(new Scorer("Emily", 19999));
rankings.addScorer(new Scorer("Michael", 18000));
rankings.addScorer(new Scorer("Madison", 17000));
assertEquals("Jacob", rankings.getTop().getName());
// assertEquals("Madison", rankings.getScorerOfPosition(4).getName());
// implementation of getScorerOfPosition(int) left as exercise :)
assertEquals(18000, rankings.getScoreOf("Michael"));
assertEquals(4, rankings.getSize());
}
}
With following initial implementation of Rankings and Scorer, this is actually compiles and passes:
class Scorer {
private final String name;
private final int rank;
Scorer(String name, int rank) {
this.name = name;
this.rank = rank;
}
public String getName() {
return name;
}
public int getRank() {
return rank;
}
}
class Rankings {
private final HashMap<String, Scorer> scorerByName = new HashMap<>();
private Scorer topScorer;
public Scorer getTop() {
return topScorer;
}
public void addScorer(Scorer scorer) {
if (scorerByName.get(scorer.getName()) != null)
throw new IllegalArgumentException("This version does not support duplicate names of scorers!");
if (topScorer == null || scorer.getRank() > topScorer.getRank()) {
topScorer = scorer;
}
scorerByName.put(scorer.getName(), scorer);
}
public int getSize() {
return scorerByName.size();
}
public int getScoreOf(String scorerName) {
return scorerByName.get(scorerName).getRank();
}
}
And unit test for parsing of raw data will start with following (how to download raw data should be responsibility of yet another class, to be developed and tested separately):
public class SingleFileProcessingTest {
private static String[] fileRawData;
#BeforeClass
public static void fillRawData() {
fileRawData = new String[2];
// values are from my head
fileRawData[0] = "Jacob\t20000\tEmily\t19999";
fileRawData[1] = "Michael\t18000\tMadison\t17000";
}
#Test
public void test() {
// uncomment, make compile, make pass
/*
RankingsDataParser parser = new RankingsDataParser();
parser.parse(fileRawData);
Rankings rankings = parser.getParsedRankings();
assertNotNull(rankings);
*/
}
}
I am using the Microsoft Dynamics CRM, using the Java API generated as per their tutorial and SDK downloads.
I can create, delete, and update entities with no problems.
I am now at the stage where I need to set entities to active or inactive.
I had thought that the right way to do this was roughly
public void doIt(OrganisationServicesStub stub, OptionSetValue stateValue, OptionSetValue statusValue)
{
Guid g = new Guid();
g.setGuid("abc-def-ghijkl");
Entity updateMe = new Entity();
updateMe.setId(g);
updateMe.setLogicalName("ei_teacherdetails");
AttributeCollection updateCollection = new AttributeCollection();
updateCollection.addKeyValuePairOfstringanyType(pair("statecode", stateValue));
updateCollection.addKeyValuePairOfstringanyType(pair("statuscode", statusValue));
updateMe.setAttributes(updateCollection);
update.setEntity(updateMe);
stub.update(update);
}
public static KeyValuePairOfstringanyType pair(String key, Object value)
{
KeyValuePairOfstringanyType attr = new KeyValuePairOfstringanyType();
attr.setKey(key);
attr.setValue(value);
return attr;
}
The above code has been tested and works for updating any attributes except the state/status ones. When I try the above code, however, (i.e. the code that tries to update the state/status), I get the following error (calling with state/status values of 1 and 2 respectively. I got those values by looking at existing Invalid entries in the CRM dumped through the same api, so I am (almost) certain that they are correct.
org.apache.axis2.AxisFault: 2 is not a valid status code for state code ei_teacherdetailsState.Active
I have noticed that in other languages, there is a SetState request, but I don't find a similar one in Java.
If anyone has been down this path before me, I'd greatly appreciate any assistance you could give.
It turns out that the correct answer is as follows, as best I can tell....
private void doIt(OrganizationServiceStub stub, OptionSetValue state, OptionSetValue status)
{
OrganizationRequest request = new OrganizationRequest();
request.setRequestName("SetState");
ParameterCollection collection = new ParameterCollection();
collection.addKeyValuePairOfstringanyType(pair("State", state));
collection.addKeyValuePairOfstringanyType(pair("Status", status));
request.setParameters(collection);
Guid g = new Guid();
g.setGuid("abc0def-ghi");
EntityReference ref = new EntityReference();
ref.setId(g);
ref.setLogicalName("ei_teacherdetails");
collection.addKeyValuePairOfstringanyType(pair("EntityMoniker", ref));
Execute exe = new Execute();
exe.setRequest(request);
stub.execute(exe);
}
Which is pretty obscure, I think. Especially I like that there's a parameter called "EntryMoniker". Anyway, I leave this answer here just in case some other poor soul ends up having to deal with this MS CRM intricacy.
I'm working on localization for a program I've written with a couple other guys. Most of the strings now load in the appropriate language from an ini file. I'm trying to do the same with the format of currency in the program. However, I'm getting a runtime exception as soon as I attempt to launch the application.
I'm using the Locale object as a parameter to a few NumberFormat.getCurrencyInstance()'s, like so:
private static final NumberFormat decf;
static
{
decf = NumberFormat.getCurrencyInstance(Lang.cLocale);
decf.setRoundingMode(RoundingMode.HALF_UP);
}
Lang is the class which contains all the localization stuff. The code the IDE complains about at attempted runtime is public static Locale cLocale = new Locale(GUI.DB_info[19],GUI.DB_info[20]);
GUI is the class the GUI is contained in, and where we decided to construct the DB_info array (which itself just contains information loaded from a remote database in another class). DB_info[19] is the language code (es right now) and DB_info[20] is the country code (US). The array elements are being properly filled-- or were, I can't get far enough into the program to tell right now; but nothing has changed with the code for filling DB_info.
The full exception is as follows:
Exception in thread "main" java.lang.ExceptionInInitializerError
at greetingCard.GUI.<clinit>(GUI.java:118)
Caused by: java.lang.NullPointerException
at java.util.Locale.<init>(Unknown Source)
at java.util.Locale.<init>(Unknown Source)
at greetingCard.Lang.<clinit>(Lang.java:13)
... 1 more
The line in GUI referenced is: static String welcome = Lang.L_WELCOME + ", " + empName;, and Lang.java basically looks like this:
// Set locale for currency display
public static Locale cLocale = new Locale(GUI.DB_info[19],GUI.DB_info[20]); // language, country
// Employee specific strings
public static String L_AMT_REMAIN = "";
public static String L_AMT_TEND = "";
public static String L_APPROVED = "";
public static String L_ARE_YOU_SURE = "";
[...]
public static void Main(String emp_lang)
{
String header = "";
if (emp_lang.equals("ENG"))
{
header = "ENG";
}
else if (emp_lang.equals("SPA"))
{
header = "SPA";
}
else if (emp_lang.equals("FRE"))
{
header = "FRE";
}
else if (emp_lang.equals("GER"))
{
header = "GER";
}
else
{
header = "ENG";
}
try
{
Ini ini = new Ini(new File("C:/lang.ini"));
L_AMT_REMAIN = ini.get(header, "L_AMT_REMAIN");
L_AMT_TEND = ini.get(header, "L_AMT_TEND");
L_APPROVED = ini.get(header, "L_APPROVED");
L_ARE_YOU_SURE = ini.get(header, "L_ARE_YOU_SURE");
[...]
L_WELCOME = ini.get(header, "L_WELCOME");
L_WELCOME2 = ini.get(header, "L_WELCOME2");
L_XACT_CHNG = ini.get(header, "L_XACT_CHNG");
L_YES = ini.get(header, "L_YES");
System.err.println("Employee Language: " + header);
}
catch (InvalidFileFormatException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
} // end public static void main
That's for the majority of the strings to be displayed in different languages. There is another method inside Lang that loads some other strings, independent of the first set. I don't believe it factors into this problem but I can post it if needed.
The order in which these classes/methods get launched is as follows:
GUI.Main calls the Login class, which calls a CreateLogin method. That method calls Clients.main, which gets the DB_info array from GUI passed to it. Clients fills the DB_info array. Lang.other is then called (to get language-specific strings for the login page), and the Login buttons and labels are created. Once a login is successful, the perferred language of the employee logging in (from a DB) is passed to Lang.main to load the other strings (hence the emp_lang being passed in the code above).
Up until I added the code for the Locale object, all of this worked fine. Now I get the ExceptionInInitializerError exception. Anyone know what's going on?
BTW, for loading from the ini file I'm using ini4j. Some forum posts I found while googling suggest this is a problem with that, but I don't see how it relates to the problem with Locale objects. The ini stuff works (worked) fine.
Sounds like you have a cycle in your static initializers, so something is not initialized yet.
GUI calls Lang's static initializer before getting Lang.L_WELCOME. Lang calls GUIs static initializer in line 2. Your exception trace makes it look like GUI calls Langs static initializer for some reason.
In all, cycles like this mean that someone is going to reference a statically initialized object and get null instead of what they expected to get. In this case, I suspect Lang.java, line 2, is passing two null pointers to the Locale constructor.
As Keith notes, you have a static initializer cycle. To help future readers...
To minimize these bugs, initialize (simple) constants (with no or minimal constructors) before (complex) variables, so here String before Locale – less room for cycles to cause problems.
Debugging-wise, NullPointerException on a static field and 2 <clinit> in stack trace, with the earlier class appearing in the failing line, are the clues that this is an uninitialized field caused by a static initializer cycle.