I use Titan in a small Ubuntu server cloud with size 3 and deployed a Rexster extension to to $TITAN_HOME/ext. However, if I try to call an endpoint of the extension I get
{"message":"An error occurred while generating the response object","error":null}
which is not very helpful. How can I get more verbose output to see what is going wrong here? In addition, error null seems strange to me. Any ideas what can cause it?
edit:
I wrapped the whole execution of the extension that causes the errors in a try-catch-everything block:
#ExtensionNaming(
namespace = GraphityExtension.EXT_NAMESPACE,
name = "unfollow")
public class RemoveFollowshipExtension extends GraphityExtension {
#ExtensionDefinition(
extensionPoint = ExtensionPoint.GRAPH)
#ExtensionDescriptor(
description = "Removes a followship between two users.")
public
ExtensionResponse
unfollow(
#RexsterContext RexsterResourceContext content,
#RexsterContext Graph graph,
#ExtensionRequestParameter(
name = "following",
description = "identifier of the user following") String idFollowing,
#ExtensionRequestParameter(
name = "followed",
description = "identifier of the user followed") String idFollowed) {
try {
Graphity graphity = getGraphityInstance((TitanGraph) graph);
Map<String, String> map = new HashMap<String, String>();
try {
map.put(KEY_RESPONSE_VALUE, String.valueOf(graphity
.removeFollowship(idFollowing, idFollowed)));
return ExtensionResponse.ok(new JSONObject(map));
} catch (UnknownFollowingIdException | UnknownFollowedIdException e) {
return ExtensionResponse.error(e);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return ExtensionResponse.error(sw.toString());
}
}
but keep getting
{"message":"","error":null}
on client side. The rexstitan.log contains warnings concerning these errors:
com.tinkerpop.rexster.GraphResource - The [graphity:unfollow+*] extension raised an error response.
which is nice to know but not very detailed.
You usually get that error if there is some failure during invocation of your extension. Usually, the console where Rexster is running should provide some log messages that explain the cause and have a stack trace.
In the event that you are not seeing those for some reason, I would try to do your own logging in your extension and possibly trap exceptions in your code more generally (and logging in the catch clause) until you can see the error.
Related
I have a strange behaviour in my java code I would like to ask some advice.
In a multithreading application I wrote this code:
scratchDir.resolve(directoryTree).toFile().mkdirs();
For a bug the Object scratchDir is null, I was expecting a stack trace on the logs but there's nothing about the error.
I have checked the code and I never try to catch the NullPointerException.
Here is the complete method code:
#Override
public void write(JsonObject jsonObject) throws FileSystemException {
Path directoryTree = getRelativePath();
scratchDir.resolve(directoryTree).toFile().mkdirs();
String newFileName = getHashFileName(jsonObject);
Path filePath = scratchDir.resolve(directoryTree).resolve(newFileName);
logger.debug("Write new file Json {} to persistent storage dir {}", newFileName, scratchDir);
File outputFile = filePath.toFile();
if (outputFile.exists()) {
throw new FileAlreadyExistsException(filePath.toString());
}
try (FileWriter fileWriter = new FileWriter(outputFile)) {
fileWriter.write(jsonObject.toString());
fileWriter.flush();
} catch (Exception e) {
logger.error(e);
}
}
Why I don't have the exception in my logs?
Why are you doing this?
The proper way to do this is:
Files.createDirectories(scratchDir.resolve(directoryTree));
don't mix old and new API. The old mkdirs() api DEMANDS that you check the return value; if it is false, the operation failed, and you do not get the benefit of an exception to tell you why. This is the primary reason for why there is a new API in the first place.
Are you sure you aren't confused - and that is the actual problem? The line as you have it will happily do absolutely nothing whatsoever (no directories, and no logs or exceptions). The line above will throw if it can't make the directories, so start there.
Then, if that line IS being run and nothing is logged, then you've caught the NPE and discarded it, someplace you didn't paste.
I am trying to create a simple XML in string format but I cannot seem to get Eclipse to play along as it keeps giving me a "cannot convert from void to String" error warning for this code (I followed along this relatively recent post on Stackoverflow about how to add a tag for an xml version.) Here is my example code:
final Xstream xstream = new Xstream();
final Person myPerson = new Person();
Writer writer = new StringWriter();
try {
writer.write("<?xml version=\"1.0\"?>");
} catch (final IOException e) {
e.printStackTrace();
System.exit(0); //just for testing sakes
}
final String xmlResponse = xstream.toXML(myPerson, writer); // the line that has the error in Eclipse
For the obvious answer of "Maybe you aren't actually making an object for myPerson," the code I have for Person is:
public class Person{
public final String name;
Person(){
name = "EmptyName";
}
}
I have searched the documentation and have found nothing about this error that would help. However, there is in the source for Xstream the method void toxml(Xstream, Object, Writer) which could potentially be the issue. The other thing it might be is escaping the quotation marks in the string could also be the issue, but I do not have a way around that. Plus removing the quotations and escapes doesn't fix the issue.
Any help in solving this would be appreciated. Xstream version 1.4.10 in case that matters.
If you look at the documentation for toXML, it returns void, means there is no return type and hence you see that error in Eclipse.
You can simply write:
xstream.toXML( myPerson, writer );
Remove String xmlResponse =
and then you can assign the xml to xmlResponse using :
final String xmlResponse = ( (StringWriter)writer ).getBuffer().toString();
I'm writing an add-on that opens a dialog and I need to access the currently opened text document but I don't know how get it.
I'm using the OpenOffice plug-in in NetBeans and I started from an Add-on project. It created a class that gives me a XComponentContext instance but I don't know how to use it to get a OfficeDocument instance of the current document.
I've been googling for some time and I can't find any example that uses an existing, opened, document. They all start from a new document or a document that is loaded first so they have an URL for it.
I gave it a try based on the OpenOffice wiki (https://wiki.openoffice.org/wiki/API/Samples/Java/Office/DocumentHandling) and this is what I came up with:
private OfficeDocument getDocument() {
if (this.officeDocument == null) {
try {
// this causes the error
XMultiComponentFactory xMultiComponentFactory = this.xComponentContext.getServiceManager();
Object oDesktop = xMultiComponentFactory.createInstanceWithContext("com.sun.star.frame.Desktop", this.xComponentContext);
XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, oDesktop);
String url = "private:factory/swriter";
String targetFrameName = "_self";
int searchFlags = FrameSearchFlag.SELF;
PropertyValue[] propertyValues = new PropertyValue[1];
propertyValues[0] = new PropertyValue();
propertyValues[0].Name = "Hidden";
propertyValues[0].Value = Boolean.TRUE;
XComponent xComponent = xComponentLoader.loadComponentFromURL(url, targetFrameName, searchFlags, propertyValues);
XModel xModel = UnoRuntime.queryInterface(XModel.class, xComponent);
this.officeDocument = new OfficeDocument(xModel);
} catch (com.sun.star.uno.Exception ex) {
throw new RuntimeException(ex);
}
}
return this.officeDocument;
}
But there is something strange going on. Just having this method in my class, even if it's never been called anywhere, causes an error when adding the add-on.
(com.sun.star.depoyment.DeploymentDescription){{ Message = "Error during activation of: VaphAddOn.jar", Context = (com.sun.star.uno.XInterface) #6ce03e0 }, Cause = (any) {(com.sun.star.registry.CannotRegisterImplementationException){{ Message = "", Context = (com.sun.star.uno.XInterface) #0 }}}}
It seems this line causes the error:
XMultiComponentFactory xMultiComponentFactory = this.xComponentContext.getServiceManager();
I have no idea how to preceed.
I posted this question on the OpenOffice forum but I haven't got a response there. I'm trying my luck here now.
Use this in your code to get the current document:
import com.sun.star.frame.XDesktop;
...
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, oDesktop);
XComponent xComponent = xDesktop.getCurrentComponent();
I opened the BookmarkInsertion sample in NetBeans and added this code to use the current document instead of loading a new document.
As far as the error, there may be a problem with how it is getting built. A couple of things to check:
Does the Office SDK version match the Office version? Check version number and whether it's 32- or 64-bit.
Make sure that 4 .jar files (juh.jar, jurt.jar, unoil.jar, ridl.jar) are shown under Libraries in NetBeans, because they need to be included along with the add-on.
If you get frustrated with trying to get the build set up correctly, then you might find it easier to use python, since it doesn't need to be compiled. Also python does not require queryInterface().
I am new to the Stack Overflow forum. I have a question in remediating the fortify scan issues.
HP Fortify scan reporting the Resource Injection issue for following code.
String testUrl = "http://google.com";
URL url = null;
try {
url = new URL(testUrl);
} catch (MalformedURLException mue) {
log.error("MalformedUrlException URL " + testUrl + " Exception : " + mue);
}
In the above code fortify showing Resource injection in line => url = new URL(testUrl);
I have done following code changes for URL validation using ESAPI to remediate this issue,
String testUrl = "http://google.com";
URL url = null;
try {
String canonURL = ESAPI.encoder().canonicalize(strurl, false, false);
if(ESAPI.validator().isValidInput("URLContext", canonURL, "URL", canonURL.length(), false)) {
url = new URL(canonURL);
} else {
log.error("In Valid script URL passed"+ canonURL);
}
} catch (MalformedURLException mue) {
log.error("MalformedUrlException URL " + canonURL + " Exception : " + mue);
}
However, still Fortify scan reporting as en error. It is not remeditaing this issue. Anything am doing wrong?
Any solution will help lot.
Thanks,
Marimuthu.M
I think that the real issue here is not that the URL may be somehow malformed, but, that the URL may not reference a valid site. More specifically, if I, the bad guy, am able to cause your URL to point to my web site, then you obtain data from my location that is not tested and I can return data that may be used to compromise your system. I might use that to say return a record for "bob the bad guy" that makes bob look like a good guy.
I suspect that in your code you do not set a hard coded value in a string, since this is usually described with words such as
When an application permits a user input to define a resource, like a
file name or port number, this data can be manipulated to execute or
access different resources.
(see https://www.owasp.org/index.php/Resource_Injection)
I think that the proper response will be some combination of:
Do not get the result from the user, but, use the input to choose from your own internal list.
Argue that the value came from a trusted source. For example, read from a strictly controlled database or configuration file.
You do not need to remove the warnings, you need to demonstrate that you understand the risk and indicate why it is OK to use the value in your case.
boolean isValidInput(java.lang.String context,
java.lang.String input,
java.lang.String type,
int maxLength,
boolean allowNull)
throws IntrusionException
type filed in isValidInput function defines a Regular expression or pattern to match with your testUrl.
Like:
try {
ESAPI.validator().getValidInput("URI_VALIDATION", requestUri, "URL", 80, false);
} catch (ValidationException e) {
System.out.println("Validation exception");
e.printStackTrace();
} catch (IntrusionException e) {
System.out.println("Inrusion exception");
e.printStackTrace();
}
It will pass if requestUri matches pattern defined in validation.properties under Validator.URL and its length is less than 80.
Validator.URL=^(ht|f)tp(s?)\:\/\/0-9a-zA-Z(:(0-9))(\/?)([a-zA-Z0-9\-\.\?\,\:\'\/\\\+=&%\$#_])?$
This is piggybacking on Andrew's answer, but the problem Fortify is warning you of is user control of a URL. If your application later decides to make connections to that website, and it is untrusted, this is an issue.
If this is an application where you care more about sharing public URIs, than you'll have to accept the risk, and make sure users are properly trained on the inherent risk, as well as make sure if you redisplay those URLs, that someone doesn't try to embed malicious data.
I've noticed that the following works on PC but not inside the Android simulator.
Logger logger = Logger.getLogger("foo");
logger.log(Level.INFO, "Number is: {0}", new Object[]{new Integer(42)});
It just prints
Number is: {0}
Why does this fail for android?
I found a solution in a roundabout way. Ultimately, I think there is a Formatter somewhere in the default android logging implementation which is rendering just the message, ignoring the params. You should be able to use the Logging API to install a formatter of your own design.
I had already installed a new Handler for a totally separate reason. The source I used is available here: http://4thline.org/projects/download/misc/
The handler is in the teleal-common-1.0.14-source.tar.gz archive. Follow the path to src\main\java\org\fourthline\android\util\FixedAndroidHandler.java.
This site also provides code to install this handler, but it's in a different archive: sash-1.0-SNAPSHOT.tar.gz. Locate 1.0\src\main\java\org\teleal\common\logging\LoggingUtil.java.
You can install this handler by making this call somewhere in your app startup code:
LoggingUtil.resetRootHandler(new FixedAndroidHandler());
What I found was that the Formatter for this Handler is embedded as an anonymous class inside the Handler. How convenient. I could see that the Formatter did not process the parameters passed in via the LogRecord. I just added an "else-if" condition:
private static final Formatter THE_FORMATTER = new Formatter() {
#Override
public String format(LogRecord r) {
String msg = r.getMessage();
Object[] params = r.getParameters();
Throwable thrown = r.getThrown();
if (thrown != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
sw.write(r.getMessage());
sw.write("\n");
thrown.printStackTrace(pw);
pw.flush();
return sw.toString();
} else if ((params != null) && (params.length > 0) && (msg.indexOf("{0") >= 0)) {
return MessageFormat.format(msg, params);
} else {
return r.getMessage();
}
}
};
The if test is consistent with other log formatting code I've seen. In theory you should be able to take a more direct approach of installing a similar Formatter to an existing Handler. I haven't tried this myself due to the fact that the above solution is working for me.
You can accomplish the same String formatting using the static String.format(String format, Object... args) method:
Log.d(TAG, String.format("Number is: %d", new Integer(42)));
Use:
android.util.Log.i(TAG, "Number is: " + number);
See http://developer.android.com/reference/android/util/Log.html