Creating Markers and Problems in Eclipse Plugin - java

I have been doing a fair amount of research but am having a hard time understanding the relation between IProblem and IMarker. I have been able to create problems and add markers but the two do not seem to be connected. Are problems and markers independent? At first I was thinking that if I add problems to ReconcileContext the markers would appear automatically but that does not appear to be the case. Does anyone know if I am doing something wrong?
SecureCompilationParticipant.java:
public class SecureCompilationParticipant extends CompilationParticipant {
public boolean isActive(IJavaProject project) {
return true;
}
#Override
public void reconcile(ReconcileContext context) {
// Call Parent
super.reconcile(context);
// Used in expression loop
int start, end, line;
String fileName;
// Check to see if content has changed
IJavaElementDelta elementDelta = context.getDelta();
IJavaElement element = elementDelta.getElement();
if((elementDelta.getFlags() & IJavaElementDelta.F_CONTENT) != 0) {
System.out.printf("The content of %s has changed%n",
element.getElementName());
try {
CompilationUnit compilation = context.getAST8();
NodeVisitor visitor = new NodeVisitor();
compilation.accept(visitor);
// Iterate through expressions
for (ExpressionStatement expressionStatement : visitor.getExpressionStatements()) {
start = expressionStatement.getStartPosition();
end = start + expressionStatement.getLength();
line = compilation.getLineNumber(start - 1);
fileName = element.getElementName();
System.out.printf("Expression: %s%n", expressionStatement.getExpression().toString());
CategorizedProblem[] problems = new CategorizedProblem[0];
ArrayList<CategorizedProblem> problemList = new ArrayList<CategorizedProblem>();
// Put problems
SecureCodingProblem problem = new SecureCodingProblem(fileName);
problem.setSourceStart(start);
problem.setSourceEnd(end);
problem.setSourceLineNumber(line);
problemList.add(problem);
context.putProblems(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, problemList.toArray(problems));
// Create marker
IResource resource = element.getUnderlyingResource();
IMarker marker = resource.createMarker(IMarker.PROBLEM);
marker.setAttribute(IMarker.MESSAGE, "This is a test marker");
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
marker.setAttribute(IMarker.LINE_NUMBER, line);
marker.setAttribute(IMarker.LOCATION, String.format("Line %d", line));
}
} catch (JavaModelException e) {
// From CompilationUnit compilation = context.getAST8();
e.printStackTrace();
} catch (CoreException e) {
// From IMarker marker = resource.createMarker(IMarker.PROBLEM);
e.printStackTrace();
}
}
}
}
SecureCodingProblem.java:
public class SecureCodingProblem extends CategorizedProblem {
private int m_sourceStart;
private int m_sourceEnd;
private int m_sourceLineNumber;
private char[] m_fileName;
public SecureCodingProblem(String fileName) {
m_fileName = fileName.toCharArray();
}
#Override
public String[] getArguments() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getID() {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getMessage() {
// TODO Auto-generated method stub
return "This is a problem";
}
#Override
public char[] getOriginatingFileName() {
// TODO Auto-generated method stub
return m_fileName;
}
#Override
public int getSourceEnd() {
// TODO Auto-generated method stub
return m_sourceEnd;
}
#Override
public int getSourceLineNumber() {
// TODO Auto-generated method stub
return m_sourceLineNumber;
}
#Override
public int getSourceStart() {
// TODO Auto-generated method stub
return m_sourceStart;
}
#Override
public boolean isError() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isWarning() {
// TODO Auto-generated method stub
return true;
}
#Override
public void setSourceEnd(int sourceEnd) {
m_sourceEnd = sourceEnd;
}
#Override
public void setSourceLineNumber(int lineNumber) {
m_sourceLineNumber = lineNumber;
}
#Override
public void setSourceStart(int sourceStart) {
m_sourceStart = sourceStart;
}
#Override
public int getCategoryID() {
// TODO Auto-generated method stub
return CategorizedProblem.CAT_CODE_STYLE;
}
#Override
public String getMarkerType() {
// TODO Auto-generated method stub
return IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER;
}
}

IProblem is specific to the Java Development Tools whereas IMarker can be used for any file in the workspace.
The JavaDoc for IProblem says:
Note: the compiler produces IProblems internally, which are turned
into markers by the JavaBuilder so as to persist problem descriptions.
This explains why there is no API allowing to reach IProblem detected
when compiling. However, the Java problem markers carry equivalent
information to IProblem, in particular their ID (attribute "id") is
set to one of the IDs defined on this interface.

Related

How to implement a custom DataStoreFactory for use with Google APIs using OAuth2?

I'm trying to implement a custom DataStoreFactory as mentioned in the docs here so that I can authenticate with Google APIs and store my access/refresh tokens in my database, but I can't find any documentation or examples of a custom implementation e.g.
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new MyCustomDatastoreFactory() )
.setAccessType("offline")
.build();
If I implement the DataStoreFactory interface, it gives me one method to implement:
import java.io.IOException;
import java.io.Serializable;
import com.google.api.client.util.store.DataStore;
import com.google.api.client.util.store.DataStoreFactory;
public class MyCustomDatastoreFactory implements DataStoreFactory {
#Override
public <V extends Serializable> DataStore<V> getDataStore(String arg0) throws IOException {
...
}
}
The DataStore object has several methods that need to be implemented, but I'm not sure where and how exactly I need to use this to retrieve and store my credentials:
new DataStore<Serializable>() {
#Override
public DataStore<Serializable> clear() throws IOException {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean containsKey(String arg0) throws IOException {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean containsValue(Serializable arg0) throws IOException {
// TODO Auto-generated method stub
return false;
}
#Override
public DataStore<Serializable> delete(String arg0) throws IOException {
// TODO Auto-generated method stub
return null;
}
#Override
public Serializable get(String arg0) throws IOException {
// TODO Auto-generated method stub
return null;
}
#Override
public DataStoreFactory getDataStoreFactory() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getId() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean isEmpty() throws IOException {
// TODO Auto-generated method stub
return false;
}
#Override
public Set<String> keySet() throws IOException {
// TODO Auto-generated method stub
return null;
}
#Override
public DataStore<Serializable> set(String arg0, Serializable arg1) throws IOException {
// TODO Auto-generated method stub
return null;
}
#Override
public int size() throws IOException {
// TODO Auto-generated method stub
return 0;
}
#Override
public Collection<Serializable> values() throws IOException {
// TODO Auto-generated method stub
return null;
}
};
There is also DataStoreCredentialRefreshListener class, but do I need to implement that and associate it with my DataStoreFactory or DataStore so that it will automatically update my DB with new tokens?

How to Correctly Mock a WebSocket session?

I have created a simple websocket application using springBoot. I am new to Mockito and I am trying to unit test the behaviour of following class with mockito and junit.
#Component
public class TextHandler extends TextWebSocketHandler {
WebSocketSession session;
#Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {
// send message
if (session.isOpen()) {
try {
session.sendMessage(new TextMessage("Hello from the websocket"));
} finally {
session.close();
}
} else {
System.out.println("no open session available");
}
}
I created a stub for the session under test package as follows.
#Component
public class WebSocketSessionStub implements WebSocketSession{
#Override
public String getId() {
return "SESSION1";
}
#Override
public URI getUri() {
// TODO Auto-generated method stub
return null;
}
#Override
public HttpHeaders getHandshakeHeaders() {
// TODO Auto-generated method stub
return null;
}
#Override
public Map<String, Object> getAttributes() {
// TODO Auto-generated method stub
return null;
}
#Override
public Principal getPrincipal() {
// TODO Auto-generated method stub
return null;
}
#Override
public InetSocketAddress getLocalAddress() {
// TODO Auto-generated method stub
return null;
}
#Override
public InetSocketAddress getRemoteAddress() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getAcceptedProtocol() {
// TODO Auto-generated method stub
return null;
}
#Override
public void setTextMessageSizeLimit(int messageSizeLimit) {
// TODO Auto-generated method stub
}
#Override
public int getTextMessageSizeLimit() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void setBinaryMessageSizeLimit(int messageSizeLimit) {
// TODO Auto-generated method stub
}
#Override
public int getBinaryMessageSizeLimit() {
// TODO Auto-generated method stub
return 0;
}
#Override
public List<WebSocketExtension> getExtensions() {
// TODO Auto-generated method stub
return null;
}
#Override
public void sendMessage(WebSocketMessage<?> message) throws IOException {
// TODO Auto-generated method stub
}
#Override
public boolean isOpen() {
System.out.println("isOpen");
return true;
}
#Override
public void close() throws IOException {
// TODO Auto-generated method stub
}
#Override
public void close(CloseStatus status) throws IOException {
// TODO Auto-generated method stub
}
}
Following is my unit test class.
#RunWith(SpringRunner.class)
#SpringBootTest
public class TextHandlerTest {
#Autowired
TextHandler textHandler;
#Mock
WebSocketSessionStub ws;
#Mock
WebSocketMessage<TextMessage> webSocketMessage;
TextMessage textMsg = new TextMessage("Test Message".getBytes());
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
textHandler.handleMessage(ws, textMsg);
}
#Test
public void verifyCallToIsOpenConnection() throws Exception {
verify(ws, times(1)).isOpen();
System.out.println("isOpen " + ws.isOpen());
}
}
Above test passes, however isOpen evaluates to false. Therefore I cannot verify the sendMessage method call. How can I rectify it?
You can mock WebSocketSession and inject it into TextHandler#handleTextMessage.
/*
* You don't need spring context while mocking.
* Hence No need to have spring runner.
*/
#RunWith(MockitoJunitRunner.class)
public class TextHandlerTest {
#Test
public void verifyCallToIsOpenConnection() {
WebSocketSession session = mock(WebSocketSession.class);
TextMessage textMsg = new TextMessage("Test Message".getBytes());
when(session.isOpen()).thenReturn(true);
TextHandler textHandler = new TextHandler();
// Pass the mocked session object here
textHandler. handleTextMessage(session, textMsg);
// Now you can verify if session.sendMessage() was called or not
verify(session, times(1)).sendMessage(textMsg);
}
}

Breaking a while-loop with a stop-command

I'm trying to make a Discord-Bot which allows you to ping certain servers. I want to ping a server (which is offline) until it comes back online. So far so good.
Now I want to add a "!stop" command which canceles this process because of whatever reason.
public class cmdping implements Commands{
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
public void action(String[] args, MessageReceivedEvent event) {
// TODO Auto-generated method stub
if((args.length == 3)) {
switch (args[2]) {
//Pings the server until it comes back online (won't work while it's online).
case "-t":
try{
int i = 0;
int q = 0;
InetAddress address = InetAddress.getByName(args[0]);
event.getTextChannel().sendMessage("Pinging _" + args[0] + " _(**" + args[1] + "**)_ ....._\n ").queue();
boolean reachable = address.isReachable(2500);
if (reachable) {
event.getTextChannel().sendMessage("Server is online.").queue();
i++;
q++;
} else {
while(!address.isReachable(2500)) {
event.getTextChannel().sendMessage("_"+args[0] + "_ (**"+ args[1] +"**) isn't communicating.").queue();
q++;
}
double outcome = 0;
outcome = i/q*100;
event.getTextChannel().sendMessage(q+" Packages were sent. The server responded to *" + i + ". " +i+"/"+q+" --> **"+outcome+"%**").queue();
i = 0;
q=0;
}
} catch (Exception e){
e.printStackTrace();
}
break;
default:
event.getTextChannel().sendMessage("Wrong arguments.").queue();
break;
}
} else {
event.getTextChannel().sendMessage("Command is not complete.").queue();
}
}
Here is the stopcmd class
public class cmdstop implements Commands {
public boolean called(String[] args, MessageReceivedEvent event) {
// TODO Auto-generated method stub
return false;
}
public void action(String[] args, MessageReceivedEvent event) {
// TODO Auto-generated method stub
}
public void executed(boolean safe, MessageReceivedEvent event) {
// TODO Auto-generated method stb
System.out.println("[INFO] Command 'stop' just got used!");
}
public String help() {
// TODO Auto-generated method stub
return null;
} }
What would I have to do to implement the stop command? I've tried out multiple things already which didn't work out for me.
EDIT: CommandListener & CommandHandler
public class commandListener extends ListenerAdapter {
public void onMessageReceived(MessageReceivedEvent event) {
if(event.getMessage().getContentRaw().startsWith(STATIC.PREFIX) && (event.getMessage().getAuthor().getId() != event.getJDA().getSelfUser().getId())) {
commandHandler.handleCommand(CommandParser.parser(event.getMessage().getContentRaw(), event));
}
} }
public class commandHandler {
public static final CommandParser parse = new CommandParser();
public static HashMap<String, Commands> commands = new HashMap<String, Commands>();
public static void handleCommand(CommandParser.commandContainer cmd) {
if(commands.containsKey(cmd.invoke)) {
boolean safe = commands.get(cmd.invoke).called(cmd.args, cmd.event);
if (!safe) {
commands.get(cmd.invoke).action(cmd.args, cmd.event);
commands.get(cmd.invoke).executed(safe, cmd.event);
} else {
commands.get(cmd.invoke).executed(safe, cmd.event);
}
}
}}
Now there is another problem. During the while-loop it doesn't detect any other commands.

ZuulFallbackProvider not getting invoked

I am trying to have a fallback if Zuul does not find a service. I have the a ZuulSever with the below code:
#SpringBootApplication
#EnableZuulProxy
#EnableDiscoveryClient
public class ZuulServerApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulServerApplication.class, args);
}
#Bean
public ZuulFallbackProvider fallBackProvider() {
return new ZuulFallbackProvider() {
#Override
public ClientHttpResponse fallbackResponse() {
return new ClientHttpResponse() {
#Override
public HttpHeaders getHeaders() {
return null;
}
#Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream("Hello".getBytes());
}
#Override
public String getStatusText() throws IOException {
// TODO Auto-generated method stub
return "Service Down";
}
#Override
public HttpStatus getStatusCode() throws IOException {
// TODO Auto-generated method stub
return HttpStatus.OK;
}
#Override
public int getRawStatusCode() throws IOException {
// TODO Auto-generated method stub
return 200;
}
#Override
public void close() {
// TODO Auto-generated method stub
}
};
}
#Override
public String getRoute() {
// TODO Auto-generated method stub
return "*";
}
};
}
}
When the service in my route is up and running, I am able to get the output. But when I bring down the service in the route, I expected the fallback to kick in. But I still see an error message instead of the fallback message. Why is the fallback not invoked? I am using Dalston Release version.
If you configure Zuul to directly connect to an URL for your route, it will use SimpleHostRoutingFilter, which will (almost) always return a 500 in case of an error. Any FallbackProviders will not kick in.
I used a custom SimpleHostRoutingFilter instead:
public class CustomErrorHostRoutingFilter extends SimpleHostRoutingFilter {
public CustomErrorHostRoutingFilter(ProxyRequestHelper helper, ZuulProperties properties, ApacheHttpClientConnectionManagerFactory connectionManagerFactory, ApacheHttpClientFactory httpClientFactory) {
super(helper, properties, connectionManagerFactory, httpClientFactory);
}
#Override
protected ZuulException handleException(Exception ex) {
if (ex instanceof ConnectTimeoutException) {
return new ZuulException(ex, "Downstream timeout", HttpServletResponse.SC_GATEWAY_TIMEOUT, ex.getMessage());
}
if (ex instanceof IOException) {
return new ZuulException(ex, "Downstream I/O error", HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
}
return super.handleException(ex);
}
}
Some kind of configuration class is required as well:
#Configuration
#EnableZuulProxy
public class ZuulConfiguration {
#Bean
public SimpleHostRoutingFilter simpleHostRoutingFilter(ProxyRequestHelper helper,
ZuulProperties zuulProperties,
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
ApacheHttpClientFactory httpClientFactory) {
return new CustomErrorHostRoutingFilter(helper, zuulProperties, connectionManagerFactory, httpClientFactory);
}
}

How to get a variable inside a Try-Catch block and inside asynchronous method

I want to know why the method myServer() return null, and not the value "result" that is assigned to finalResult inside " public void onSuccessInMainThread(...)" I'm new to java and there are some things I don't understand
protected LemmaValidationJob finalResult;
public LemmaValidationJob myServer(){
TaskConfiguration config = new TaskConfiguration(TaskType.RELATION);
config.setLanguage(Language.EN);
try{
AnnotationManager.getInstance().getData(config,
new MainThreadCallback<LemmaValidationJob>(){
#Override
public void onSuccessInMainThread(LemmaValidationJob result){
finalResult = result;
}
#Override
public void onFailureInMainThread(Throwable cause){
// TODO Auto-generated method stub
}
});
} catch (AuthenticationRequiredException e) {
System.err.println("NO LOGIN");
e.printStackTrace();
}
return finalResult;
}
The problem is that your myServer() method probably returns before the execution of the onSuccessInMainThread() method.
If a method performs an ansychronous thread then in most cases the calling method must also have an asynchronous signature. So in this case myServer must be void, and must receive a callback as a parameter. So it will be something like
public void myServer(Consumer<LemmaValidationJob> onSuccess){
TaskConfiguration config = new TaskConfiguration(TaskType.RELATION);
config.setLanguage(Language.EN);
try{
AnnotationManager.getInstance().getData(config,
new MainThreadCallback<LemmaValidationJob>(){
#Override
public void onSuccessInMainThread(LemmaValidationJob result){
onSuccess.apply(result);
}
#Override
public void onFailureInMainThread(Throwable cause){
// TODO Auto-generated method stub
}
});
} catch (AuthenticationRequiredException e) {
System.err.println("NO LOGIN");
e.printStackTrace();
}
}

Categories