How to get the variable real type using JavaSymbolSolver - javasymbolsolver

The code is here,
class Bar {
private int a;
void aMethod() {
while (true) {
String a = "0";
a = a + "1";
}
}
}
I want to get the real type of a. I tried to use the code below,
public class GetTypeOfReference {
private static final String FILE_PATH = "src\\com\\test\\Bar.java";
public static void main(String[] args) throws FileNotFoundException {
TypeSolver typeSolver = new CombinedTypeSolver();
JavaSymbolSolver symbolSolver = new JavaSymbolSolver(typeSolver);
StaticJavaParser.getConfiguration().setSymbolResolver(symbolSolver);
CompilationUnit cu = StaticJavaParser.parse(new File(FILE_PATH));
cu.findAll(AssignExpr.class).forEach(ae -> {
ResolvedType resolvedType = ae.calculateResolvedType();
System.out.println(ae.toString() + " is a: " + resolvedType.describe());
});
}
}
But got the error,
Exception in thread "main" UnsolvedSymbolException{context='null', name='String', cause='null'}
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.convertToUsage(JavaParserFacade.java:509)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.convert(JavaParserFacade.java:567)
at com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserSymbolDeclaration.getType(JavaParserSymbolDeclaration.java:146)
at com.github.javaparser.symbolsolver.model.resolution.Value.from(Value.java:40)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
at java.base/java.util.LinkedList$LLSpliterator.tryAdvance(LinkedList.java:1253)
at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:127)
at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:502)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:488)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:476)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.AbstractJavaParserContext.solveWithAsValue(AbstractJavaParserContext.java:149)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.StatementContext.solveSymbolAsValue(StatementContext.java:135)
at com.github.javaparser.symbolsolver.resolution.SymbolSolver.solveSymbolAsValue(SymbolSolver.java:68)
at com.github.javaparser.symbolsolver.resolution.SymbolSolver.solveSymbolAsValue(SymbolSolver.java:73)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:277)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:44)
at com.github.javaparser.ast.expr.NameExpr.accept(NameExpr.java:79)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:98)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:44)
at com.github.javaparser.ast.expr.AssignExpr.accept(AssignExpr.java:135)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getTypeConcrete(JavaParserFacade.java:448)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:310)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:292)
at com.github.javaparser.symbolsolver.JavaSymbolSolver.calculateType(JavaSymbolSolver.java:250)
at com.github.javaparser.ast.expr.Expression.calculateResolvedType(Expression.java:564)
at test.GetTypeOfReference.lambda$0(GetTypeOfReference.java:32)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1378)
at test.GetTypeOfReference.main(GetTypeOfReference.java:31)
What is the right way to do this?

The answer is late but for those who are interested this is the right approach.
With javaparser 3.16.1 the result is
a = a + "1" is a: java.lang.String

Related

How to convert a GLib.Value of type GStrv (string[]) to a GLib.Variant

In the following example one class property is of type Gstrv.
With ObjectClass.list_properties() one can query the Paramspec of all properties, and with get_property() all properties can be requested as GLib.Value. How would I access the Value of type GStrv and convert it to a GLib.Variant?
My GLib version is slightly outdated, so I do not have the GLib.Value.to_variant() function available yet :( .
public class Foo: GLib.Object {
public GLib.HashTable<string, int32> bar;
public Foo() {
bar = new GLib.HashTable<string, int32>(str_hash, str_equal);
}
public string[] bar_keys { owned get { return bar.get_keys_as_array(); } }
}
int main() {
var foo = new Foo();
Type type = foo.get_type();
ObjectClass ocl = (ObjectClass) type.class_ref ();
foreach (ParamSpec spec in ocl.list_properties ()) {
print ("%s\n", spec.get_name ());
Value property_value = Value(spec.value_type);
print ("%s\n", property_value.type_name ());
foo.get_property(spec.name, ref property_value);
// next: convert GLib.Value -> GLib.Variant :(
}
foo.bar.set("baz", 42);
return 0;
}
Output:
bar-keys
GStrv
Using GLib.Value.get_boxed() seems to be working.
Example:
// compile simply with: valac valacode.vala
public class Foo: GLib.Object {
public GLib.HashTable<string, int32> bar;
public Foo() {
bar = new GLib.HashTable<string, int32>(str_hash, str_equal);
}
public string[] bar_keys { owned get { return bar.get_keys_as_array(); } }
}
public Variant first_gstrv_property_as_variant(Object obj)
{
Type class_type = obj.get_type();
ObjectClass ocl = (ObjectClass) class_type.class_ref ();
foreach (ParamSpec spec in ocl.list_properties ()) {
print ("%s\n", spec.get_name ());
Value property_value = Value(spec.value_type);
print ("%s\n", property_value.type_name ());
obj.get_property(spec.name, ref property_value);
// next: convert GLib.Value -> GLib.Variant
if(property_value.type_name () == "GStrv") {
return new GLib.Variant.strv((string[])property_value.get_boxed());
}
}
return new GLib.Variant("s", "No property of type GStrv found");
}
int main() {
var foo = new Foo();
print("%s\n", first_gstrv_property_as_variant(foo).print(true));
foo.bar.set("baz", 42);
print("%s\n", first_gstrv_property_as_variant(foo).print(true));
foo.bar.set("zot", 3);
print("%s\n", first_gstrv_property_as_variant(foo).print(true));
return 0;
}
Output:
bar-keys
GStrv
#as []
bar-keys
GStrv
['baz']
bar-keys
GStrv
['baz', 'zot']
In the generated c-code this looks as follows:
_tmp18_ = g_value_get_boxed (&property_value);
_tmp19_ = g_variant_new_strv ((gchar**) _tmp18_, -1);
Passing -1 as length to g_variant_new_strv() means the string array is considered as null terminated. Inside g_variant_new_strv() the g_strv_length() function is used to determine the length.
Hopefully it will be useful to someone else someday. :-)

Sentiment Analysis with OpenNLP

I found this description of implementing a Sentiment Analysis task with OpenNLP. In my case I am using the newest OPenNLP-version, i.e., version 1.8.0. In the following example, they use a Maximum Entropy Model. I am using the same input.txt (tweets.txt)
http://technobium.com/sentiment-analysis-using-opennlp-document-categorizer/
public class StartSentiment {
public static DoccatModel model = null;
public static String[] analyzedTexts = {"I hate Mondays!"/*, "Electricity outage, this is a nightmare"/*, "I love it"*/};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);
}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("bin/text.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "2");
tp.put(TrainingParameters.ITERATIONS_PARAM, "30");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text){
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(new String[]{text});
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}
}
In my case no matter what input String I am using, I am only getting a positive estimation of the input string. Any idea what could be the reason?
Thanks

Custom extension element in Stanza for Smack 4.1.4

I am moving my android application from asmack-android library to Smack 4.1.4. I have some PacketExtensions in the asmack version of Smack, which uses PacketExtension and PacketExtensionProvider classes to handle. Since the PacketExtension is deprecated in Smack 4.1.4, I am confused among the classes and interfaces ExtensionElement, DataPacketExtension, ExtensionElementProvider , DefaultExtensionElement. Could any one of you give me an example of creating an extension which can be added with stanza and parse back...https://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware /smack/packet/DefaultExtensionElement.htmlhttps://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware /smack/provider/ExtensionElementProvider.html
Message message = new Message();
message.setStanzaId("923442621149");
message.setType(Type.chat);
message.setBody("shanraisshan");
Log.e("message --->", message.toXML().toString());
This will produce the following stanza
<message id='923442621149' type='chat'><body>shanraisshan</body></message>
1. CUSTOM EXTENSION STANZA TYPE-1
In order to generate below custom extension stanza
<message id='923442621149' type='chat'><body>shanraisshan</body>
<reply xmlns='shayan:reply' rText='this is custom attribute'/>
</message>
where reply is a custom extension, which contains
Element (reply)
Namespace (shayan:reply)
the list of default xmpp namespaces are available at Official XMPP website
Do following steps
1. Add ReplyExtension.java in your project
ReplyExtension.java
package com.xmpp.extensions;
import org.jivesoftware.smack.packet.DefaultExtensionElement;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.provider.EmbeddedExtensionProvider;
import org.jivesoftware.smack.util.XmlStringBuilder;
import java.util.List;
import java.util.Map;
/**
* Shayan Rais (http://shanraisshan.com)
* created on 9/7/2016
*/
public class ReplyExtension implements ExtensionElement {
public static final String NAMESPACE = "shayan:reply";
public static final String ELEMENT = "reply";
String rText = null;
static final String ATTRIBUTE_REPLY_TEXT = "rText";
#Override
public String getElementName() {
return ELEMENT;
}
#Override
public String getNamespace() {
return NAMESPACE;
}
#Override
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder(this);
xml.attribute(ATTRIBUTE_REPLY_TEXT, getReplyText());
xml.closeEmptyElement();
return xml;
}
//__________________________________________________________________________________________________
public void setReplyText(String _rText) {
rText = _rText;
}
public String getReplyText() {
return rText;
}
//__________________________________________________________________________________________________
public static class Provider extends EmbeddedExtensionProvider<ReplyExtension> {
#Override
protected ReplyExtension createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content) {
ReplyExtension repExt = new ReplyExtension();
repExt.setReplyText(attributeMap.get(ATTRIBUTE_REPLY_TEXT));
return repExt;
}
}
}
2. Register ReplyExtension in your Provider Manager
ProviderManager.addExtensionProvider(ReplyExtension.ELEMENT, ReplyExtension.NAMESPACE, new ReplyExtension.Provider());
FOR SENDING MESSAGES
You can generate the custom extension stanza TYPE-1 by using following code
Message message = new Message();
message.setStanzaId("923442621149");
message.setType(Type.chat);
message.setBody("shanraisshan");
//adding custom reply extension
ReplyExtension repExt = new ReplyExtension();
repExt.setReplyText("this is custom attribute");
message.addExtension(repExt);
Log.e("message --->", message.toXML().toString());
DURING RECEIVING MESSAGES
Now during receiving custom extension stanzas, you need to cast the extension to get attribute values.
//check for message with reply extension
ExtensionElement packetExtension = message.getExtension(ReplyExtension.NAMESPACE);
ReplyExtension repExt = (ReplyExtension)packetExtension;
if(repExt!=null) {
Log.e("--->", " --- LOG REPLY EXTENSION ---");
Log.e("--->", repExt.toXML() + "");
Log.e("--->", repExt.getReplyText() + ""); //this is custom attribute
}
_______________________________________________________
2. CUSTOM EXTENSION STANZA TYPE-2
In order to generate below custom extension stanza
<message id='923442621149' type='chat'><body>shanraisshan</body>
<reply xmlns='shayan:reply'><rText>this is custom attribute</rText></reply>
</message>
FOR SENDING MESSAGES
You can generate the custom extension stanza TYPE-2 by using following code
Message message = new Message();
message.setStanzaId("923442621149");
message.setType(Type.chat);
message.setBody("shanraisshan");
//adding custom reply extension
DefaultExtensionElement repExt = new DefaultExtensionElement("reply", "shayan:reply");
repExt.setValue("rText", "this is custom attribute");
message.addExtension(repExt);
Log.e("message --->", message.toXML().toString());
DURING RECEIVING MESSAGES
DefaultExtensionElement repExt = (DefaultExtensionElement) message.getExtension("shayan:reply");
if(repExt!=null) {
Log.e("--->", " --- LOG REPLY EXTENSION ---");
Log.e(getClass().getSimpleName(), repExt.getValue("rText"));
}
Finally figured it out.... Here is the solution for it...
import org.jivesoftware.smack.packet.DefaultExtensionElement;
public class IM_FileSharing_Extension extends DefaultExtensionElement implements
IM_Commons_Extension_FileSharing {
private String fileUrl;
private String fileType;
private String base64preview;
private String fileId;
private String fileSize;
public IM_FileSharing_Extension(String fileUrl, String fileType,
String base64preview, String fileId, String fileSize) {
super(FILE_TAG, XMLNS);
this.fileUrl = fileUrl;
this.fileType = fileType;
this.base64preview = base64preview;
this.fileId = fileId;
this.fileSize = fileSize;
}
#Override
public String toXML() {
StringBuilder sb = new StringBuilder("<" + FILE_TAG + " xmlns=\""
+ XMLNS + "\" ");
sb.append(FILE_URL + "=\"" + fileUrl + "\" ");
sb.append(FILE_ID + "=\"" + fileId + "\" ");
sb.append(FILE_TYPE + "=\"" + fileType + "\" ");
sb.append(FILE_SIZE + "=\"" + fileSize + "\">");
sb.append("<" + FILE_PREVIEW_TAG + ">" + base64preview + "</"
+ FILE_PREVIEW_TAG + ">");
sb.append("</" + FILE_TAG + ">");
return sb.toString();
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public String getBase64preview() {
return base64preview;
}
public void setBase64preview(String base64preview) {
this.base64preview = base64preview;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
}
Provider for the above extension is as follows...
import java.io.IOException;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Log;
public class IM_FileSharingExtension_Provider extends
ExtensionElementProvider<IM_FileSharing_Extension> implements
IM_Commons_Extension_FileSharing {
static final String TAG = "file_extension";
#Override
public IM_FileSharing_Extension parse(XmlPullParser parser, int initialDepth)
throws XmlPullParserException, IOException, SmackException {
IM_FileSharing_Extension fileExtension = null;
boolean stop = false;
String n = null;
int evtType;
String fileUrl = null;
String fileType = null;
String fileId = null;
String fileSize = null;
while (!stop) {
evtType = parser.getEventType();
n = parser.getName();
Log.d(TAG, "n:" + n + " evt:" + evtType);
switch (evtType) {
case XmlPullParser.START_TAG:
if (FILE_TAG.equals(n)) {
fileUrl = parser.getAttributeValue("", FILE_URL);
fileType = parser.getAttributeValue("", FILE_TYPE);
fileId = parser.getAttributeValue("", FILE_ID);
fileSize = parser.getAttributeValue("", FILE_SIZE);
evtType = parser.next();
}
if (FILE_PREVIEW_TAG.equals(parser.getName())) {
String basePreview = parser.nextText();
fileExtension = new IM_FileSharing_Extension(fileUrl,
fileType, basePreview, fileId, fileSize);
}
evtType = parser.next();
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals(FILE_TAG)) {
return fileExtension;
}
evtType = parser.next();
}
}
return null;
}
}
And should be added in Provider manager as following....
ProviderManager.addExtensionProvider(
IM_Commons_Extension_FileSharing.FILE_TAG,
IM_Commons_Extension_FileSharing.XMLNS,
new IM_FileSharingExtension_Provider());

handleURI for http://AAA.BBB.CCC.DDD:8080/myapp/ uri: '' returns ambigious result (Vaadin 6)

In my Vaadin 6 application I sometimes get the following error:
SEVERE: Terminal error:
java.lang.RuntimeException: handleURI for http://AAA.BBB.CCC.DDD:8080/myapp/ uri: '' returns ambigious result.
at com.vaadin.ui.Window.handleURI(Window.java:432)
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.handleURI(AbstractCommunicationManager.java:2291)
at com.vaadin.terminal.gwt.server.CommunicationManager.handleURI(CommunicationManager.java:370)
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.handleURI(AbstractApplicationServlet.java:1099)
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.service(AbstractApplicationServlet.java:535)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Accrording to Vaadin source it occurs in the following method:
public DownloadStream handleURI(URL context, String relativeUri) {
DownloadStream result = null;
if (uriHandlerList != null) {
Object[] handlers;
synchronized (uriHandlerList) {
handlers = uriHandlerList.toArray();
}
for (int i = 0; i < handlers.length; i++) {
final DownloadStream ds = ((URIHandler) handlers[i]).handleURI(
context, relativeUri);
if (ds != null) {
if (result != null) {
throw new RuntimeException("handleURI for " + context
+ " uri: '" + relativeUri
+ "' returns ambigious result.");
}
result = ds;
}
}
}
return result;
}
I actually create a DownloadStream in a column generator (in order to display images in a table):
public class ImageColumnGenerator implements Table.ColumnGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageColumnGenerator.class);
public final static String IMAGE_FIELD = "image";
public Object generateCell(final Table aTable, final Object aItemId, final Object aColumnId) {
if (!IMAGE_FIELD.equals(aColumnId)) {
return null;
}
final BeanItem<UserProductImageBean> beanItem = (BeanItem<UserProductImageBean>)
aTable.getItem(aItemId);
final StreamResource streamResource = new StreamResource(new StreamResource.StreamSource() {
public InputStream getStream() {
return new ByteArrayInputStream(beanItem.getBean().getImageData());
}
},
beanItem.getBean().getFileName(),
MyApplication.getInstance());
LOGGER.debug("imageResource: " + streamResource);
final Embedded embedded = new Embedded("", streamResource);
return embedded;
}
}
beanItem.getBean().getImageData() is a byte array (byte[]) with image data, which I get from a web service.
MyApplication.getInstance() is defined as follows:
public class MyApplication extends Application implements ApplicationContext.TransactionListener
{
private static ThreadLocal<MyApplication> currentApplication =
new ThreadLocal<MyApplication> ();
public static MyApplication getInstance()
{
return currentApplication.get ();
}
}
What can I do in order to fix the aforementioned (severe) error?
As soon as nobody answer. I'm not at all expert in what hell it is above, but - try to find out on what kind of urls this error arise on, and do with them something before feed them to DownloadStream

Access to constant from inside grails filter DSL

Here I'm only trying to be DRY on a string key I need, but the only thing
working is putting the string directly into the assignments: request['RequestStopwatch.start'] = System.currentTimeMillis().
Any pointers?
class RequestStopwatchFilters {
def REQ_KEY = 'RequestStopwatch.start'
def filters = {
all(controller:'*', action:'*') {
before = {
log.debug(""+System.currentTimeMillis() + " " + request)
// NULL pointer exception on REQ_KEY here:
request[REQ_KEY] = System.currentTimeMillis()
}
after = { Map model ->
if (log.isDebugEnabled()) {
// NULL pointer exception on REQ_KEY here:
log.debug("Stopped request before view at " + (System.currentTimeMillis() - request[REQ_KEY]) + "ms")
}
}
afterView = { Exception e ->
if (log.isDebugEnabled()) {
// NULL pointer exception on REQ_KEY here:
log.debug("Stopped request at " + (System.currentTimeMillis() - request[REQ_KEY]) + "ms")
}
}
}
}
}
Make it as static or better as public final static, like:
class RequestStopwatchFilters {
public final static String REQ_KEY = 'RequestStopwatch.start'
}
and use it anywhere as:
RequestStopwatchFilters.REQ_KEY

Resources