I'm having trouble figuring out how to create issue a redirect to the browser after a certain condition in a Java webapp running on Tomcat. I'm sure there must be a simple solution, but my Java skills are extremely limited.
Here's the specific code I'm working with (copied from guacamole-auth-passthrough):
if (req.getParameter("username") == null {
LOG.error("username is required");
throw new GuacamoleServerException("username is required");
}
I'd like to replace that exception with a redirect back to the index page. In PHP I could simply do this:
header("Location: https://site.domain.com/",TRUE,302);
Java's not letting me off so easily, though. The best direct analog I could find is this:
response.sendRedirect("https://site.domain.com/");
However, that fails compilation with:
[ERROR] /home/dev/guacamole-client-0.9.9/extensions/guacamole-auth-passthrough/src/main/java/com/github/edouardswiac/guacamole/ext/PassthroughAuthProvider.java:[31,6] error: cannot find symbol
I've found many other examples of Java redirects (including this other stackoverflow thread), but almost all of them seem to implement separate methods to implement the redirect. As I said, my java skills are very basic, and I have no idea how to actually implement something like that to be used/called from within an if condition.
Can anyone provide some pointers on how I can correctly implement this within the condition above? I'm pretty much completely out of ideas at this point, and would very much appreciate any guidance. Thanks.
I would suggest to write response.sendRedirect() in the catch block of the exception. For example:
HttpServletResponse response = credentials.getResponse();
try{
if (req.getParameter("username") == null {
LOG.error("username is required");
throw new GuacamoleServerException("username is required");
}
catch(GuacamoleServerException e){
response.sendRedirect("https://site.domain.com/");
}
P.S. This is provided you are using Java Servlets for your purpose.
Related
I'm trying to make a program that checks avaliable positions and books the first avaliable one. I started writing it and i ran into a problem pretty early.
The problem is that when I try to connect with the site (which is https) the program doesn't do anything. It doesn't throw an error, it doesn't crash. And the weirdest thing is that it works with some https websites and with some it doesn't.
I've spent countless hours trying to resolve this problem. I tried using htmlunitdriver and it still doesn't work. Please help.
private final WebClient webc = new WebClient(BrowserVersion.CHROME);
webc.getCookieManager().setCookiesEnabled(true);
HtmlPage loginpage = webc.getPage(loginurl);
System.out.println(loginpage.getTitleText());
I'm getting really frustrated with this. Thank you in advance.
As far as i can see this has nothing to do with HttpS. It is a good idea to do some traffic analysis using Charles or Fiddler.
What you can see....
The page returned from the server as response to your first call to https://online.enel.pl/ loads some external javascript. And then the story begins:
This JS looks like
(function() {
var z = "";
var b = "766172205f3078666.....";
eval((function() {
for (var i = 0; i < b.length; i += 2) {
z += String.fromCharCode(parseInt(b.substring(i, i + 2), 16));
}
return z;
})());
})();
As you can see someone likes to hide the real javascript that gets processed.
Next step is to check the javascript after this simple decoding
It is really huge and looks like this
var _0xfbfd = ['\x77\x71\x30\x6b\x77 ....
(function (_0x2ea96d, _0x460da4) {
var _0x1da805 = function (_0x55e996) {
while (--_0x55e996) {
_0x2ea96d['\x70\x75\x73\x68'](_0x2ea96d['\x73\x68\x69\x66\x74']());
}
};
.....
Ok now we have obfuscated javascript. If you like you can start with http://ddecode.com/hexdecoder/ to get some more readable text but this was the step where i have stopped my analysis. Looks like this script does some really bad things or someone still believes in security by obscurity.
If you run this with HtmlUnit, this codes gets interpreted - yes the decoding works and the code runs. Sadly this code runs endless (maybe because of an error or some incompatibility with real browsers).
If you like to get this working, you have to figure out, where the error is and open an bug report for HtmlUnit. For this you can simply start with a small local HtmlFile and include the code from the first external javascript. Then add some log statements to get the decoded version. Then replace this with the decoded version and try to understand what is going on. You can start adding alert statements and check if the code in HtmlUnit follows the same path as browsers do. Sorry but my time is to limited to do all this work but i really like to help/fix if you can point to a specific function in HtmlUnit that works different from real browsers.
Without the URL that you are querying it is dificult to say what could be wrong. However, having worked with HTML unit some time back I found that it was failing with many sites that I needed to get data from. The site owners will do many things to avoid you using programs to access them and you might have to resort to using some lower level library like Apache HTTP components where you have more control over what is going on under the hood.
Also check if the website is constructed using JavaScript which is getting more and more popular but making it increasingly dificult to use programs to interrogate the content.
I'm developing a skill in Amazon Alexa. I'm trying to test the same using echosim.io but the problem is as below.
My Skill name is MyBot and the same is invocation name.
In echosim.io, When I say Alexa Launch MyBot, it gives the welcome response (The help response that I've coded in). When I say help, it gives me the help response that I've entered.
I've 4 intents say
FaqIntentOne
FIntentOne
FaqIntentTwo
FIntentTwo
And my Sample utterances are as below.
FaqIntentOne what is first answer
FIntentOne give me first answer
FaqIntentTwo what is second answer
FIntentTwo give me second answer
When I run these, Alexa doesn't give me a response.
I've the correct methods and the correct response set there. please let me know why it is not working for the utterances other than the built in ones.
when test in Alexa's test interface in developer.amazon.com, it is giving me the correct response.
This is quite confusing.
Below is how it looks in my code.
if ("FaqIntentOne".equals(intentName) || "FIntentOne".equals(intentName)) {
return getFirstHelp(intent, session);
}
else if ("FaqIntentTwo".equals(intentName) || "FIntentTwo".equals(intentName)) {
return getSecondHelp(intent, session);
}
Thanks
Though Amazon has referred people to echosim, it is not 'official' (it was developed by a 3rd party), so if it works in Amazon's test environment and not in echosim then it is possible that the issue is with echosim.
Otherwise I think you are going to need to look more closely at what is happening in your code, ie. debug it or put in some print statements and compare what happens when invoked in those 2 ways.
If you are running in Lambda - seems to be the most common - then you will need to take a look at CloudWatch logs.
I am using the tutorial here for pushing data and consuming, data from Azure Service Bus. When I run the example the second time, I get back an error PUT https://asbtest.servicebus.windows.net/TestQueue?api-version=2012-08 returned a response status of 409 Conflict, which is way of saying you have already a configuration with that name, so do not create it another time. Most probably, this is the guilty code
Configuration config =
ServiceBusConfiguration.configureWithWrapAuthentication(
"HowToSample",
"your_service_bus_owner",
"your_service_bus_key",
".servicebus.windows.net",
"-sb.accesscontrol.windows.net/WRAPv0.9");
ServiceBusContract service = ServiceBusService.create(config);
QueueInfo queueInfo = new QueueInfo("TestQueue");
That is recalling create() is causing the problem, I would guess. But all methods in com.microsoft.windowsazure.services.serviceBus.ServiceBusService from http://dl.windowsazure.com/javadoc/ are only create, and I am unable to find a method like
ServiceBusContract service = A_class_that_finds_existing_bus_contract.find(config);
Am I thinking the wrong way, or is there another way out. Any pointers are appreciated.
EDIT:
I realized my code example for what I was asking was config, not service bus contract. Updated it, to reflect so.
Turns out I was wrong. The create() function in ServiceBusService does not throw any exception, as I gathered from Javadocs. Also, you can create the service bus contracts multiple times, as it being only a connection. The exception arises, when you attempt to create a queue with a name that already exists. That is this line.
String path = "TestQueue";
QueueInfo queueInfo = new QueueInfo(path);
To overcome this, you can go this way.
import com.microsoft.windowsazure.services.serviceBus.Util;
...
...
Iterable<QueueInfo> iqnf = Util.iterateQueues(service);
boolean queue_created = false;
for( QueueInfo qi : iqnf )
{
if( path.toLowerCase().equals( qi.getPath() ))
{
System.out.println(" Queue already exists. Do not create one.");
queue_created = true;
}
}
if ( !queue_created ) {
service.createQueue(queueInfo);
}
Hope, this helps anybody who may be stuck on create conflicts for queue on Azure.
EDIT: Even after I got the path code, my code refused to work. Turns out there is another caveat. Azure makes all queue names in lower case. I have edited the code to use toLower() for this work around.
I upvoted Soham's Question and Answer. I did not know about lowercase though I have not verified it. It did confirm the problem I am having right now as well.
The way #Soham has addressed it is good but not good for large ServicebUs where we may have tons of Queues it's added overhead to iterate it. The only way is to catch the ServiceException which is very generic and ignore that Exception.
Example:
QueueInfo queueInfo = new QueueInfo(queName);
try {
CreateQueueResult qr = service.createQueue(queueInfo);
} catch (ServiceException e) {
//Silently ignore for now.
}
The right way would be for the Azure library to extend the ServiceException and throw "ConcflictException" for e.g. which is present in httpStatusCode of ServiceException but unfortunately it's set to Private.
Since it is not We would have to extend the ServiceException and override the httpStatusCode setter.
Again, not the best way but the library can improve if we list as feedback on their Github issues.
Note: ServiceBus is still in preview phase.
I have to interface a third party COM API into an Java application. So I decided to use Com4j, and so far I've been satisfied, but now I've run into a problem.
After running the tlbgen I have an object called IAddressCollection which according to the original API documentation conforms to the IEnum interface definition. The object provides an iterator() function that returns a java.util.Iterator<Com4jObject>. The object comes from another object called IMessage when I want to find all the addresses for the message. So I would expect the code to work like this:
IAddressCollection adrCol = IMessage.getAddressees();
Iterator<Com4jObject> adrItr = adrCol.iterator();
while(adrItr.hasNext()){
Com4jObject adrC4j = adrItr.next();
// normally here I would handle the queryInterface
// and work with the rest of the API
}
My problem is that when I attempt the adrItr.next() nothing happens, the code stops working but hangs. No exception is thrown and I usually have to kill it through the task manager. So I'm wondering is this a problem that is common with Com4j, or am I handling this wrong, or is it possibly a problem with the API?
Ok, I hate answering my own question but in this case I found the problem. The issue was the underlying API. The IAddressCollection uses a 1 based indexing instead of a 0 based as I would have expected. It didn't provide this information in the API documentation. There is an item function where I can pull the object this way and so I can handle this with
IAddressCollection adrCol = IMessage.getAddressees();
for(int i = 1; i <= adrCol.count(); i++){
IAddress adr = adrCol.item(i);
// IAddress is the actual interface that I wanted and this works
}
So sorry for the annoyance on this.
The requirement I receive is to model some existing content available on a SQL Server database using Alfresco content managment so, I create my new content model and it seems to working fine. But I've a problem with multi language: I know in Alfresco is possible for one node add multiple language (how can I do that using Java for a massive load?) but, I used also some aspects that need to be translated.
What do you usually do in that case? I thoug to follow this steps:
Create Eng content and add aspects
Create new child translted and add aspects
Is it correct? How can I make a node Multilingual programmatically (Java) and how can I add the new translate content with aspects? I took a look to Alfresco documentation but, I didn't find it, could you help me to find some documentation or tutorial about that?
UPDATE:
I'm trying to make a content multilangue:
void makeTranslation(Reference contentNodeRef, Locale locale) throws AlfrescoRuntimeException, Exception
{
try {
NodeRef nodeRef = new NodeRef("workspace://SpacesStore/" + contentNodeRef.getUuid());
MultilingualContentServiceImpl multilingualContentServiceImpl = new MultilingualContentServiceImpl();
multilingualContentServiceImpl.makeTranslation(nodeRef, locale);
}
catch (org.alfresco.error.AlfrescoRuntimeException ex) {
throw new AlfrescoRuntimeException(ex.getMessage());
}
catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
but, makeTranslation raise an nullPoint exception because MultilingualContentServiceImpl it's not initialized correctly. Any suggestion how to initialize it? I've to use spring but, how?
Any suggerstion or reply will be very helpful!
Thanks,
Andrea
You can use MultilingualContentService to add translations. But! I guess your properties should be of type d:mltext (like cm:title and cm:description are) to support multilingual content.
This means if you access alfresco using browser with english language you will see a different description as someone using german language settings in browser. This can be a little confusing because in Share there is (was?) no identifier that the property is multilingual.
If you want your translations to appear everywhere, no matter what kind of language in browser people are using, then the better approach is to define some aspect (for example ex:translatable) with as many properties as you need translations. Then you can programatically (using Java or JavaScript) use search service to find nodes you want and add the aspect to them. Finally you then add properties (translations) of that aspect to the node.
I hope this helps to clear things a bit... :)