IllegalStateException: Already connected with HttpURLConnection.setFixedLengthStreamingMode - java

I know this question has been asked a few times here but I've tried everything. It may be completely my fault as this is my first time doing this but if it is then at least I'll be able to improve.
Relevant code:
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization",
"Bot (token)");
connection.setRequestProperty("User-Agent", "https://discordapp.com/developers/docs/reference, 1.0.0");
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(connection.getContentLength());
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
break;
case HttpURLConnection.HTTP_UNAUTHORIZED:
Executor.logger.warning("Connection to Discord API does not have sufficient authorization!");
player.sendMessage(ChatColor.RED
+ "An unrelated error occured in the server, please report this to a staff member.");
return;
default:
Executor.logger.warning(
"An unknown exception occured with the HTTP Error Code: " + connection.getResponseCode());
player.sendMessage(ChatColor.RED + "Linking your accounts has failed!");
TextComponent message = new TextComponent(ChatColor.AQUA + ChatColor.BOLD.toString() + "click here!");
message.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.mcpz.net"));
player.sendMessage(
ChatColor.YELLOW + "For information on how to find your ID, " + message.toPlainText());
return;
}
Console error:
org.bukkit.command.CommandException: Unhandled exception executing command 'link' in plugin DiscordBridge v1.0.0
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at org.bukkit.craftbukkit.v1_9_R2.CraftServer.dispatchCommand(CraftServer.java:645) ~[squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.PlayerConnection.handleCommand(PlayerConnection.java:1349) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.PlayerConnection.a(PlayerConnection.java:1184) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.PacketPlayInChat.a(PacketPlayInChat.java:45) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.PacketPlayInChat.a(PacketPlayInChat.java:1) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.PlayerConnectionUtils$1.run(SourceFile:13) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_121]
at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_121]
at net.minecraft.server.v1_9_R2.SystemUtils.a(SourceFile:45) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.MinecraftServer.D(MinecraftServer.java:726) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.DedicatedServer.D(DedicatedServer.java:399) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.MinecraftServer.C(MinecraftServer.java:665) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at net.minecraft.server.v1_9_R2.MinecraftServer.run(MinecraftServer.java:564) [squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_121]
Caused by: java.lang.IllegalStateException: Already connected
at java.net.HttpURLConnection.setFixedLengthStreamingMode(Unknown Source) ~[?:1.8.0_121]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.setFixedLengthStreamingMode(Unknown Source) ~[?:1.8.0_121]
at uk.co.harieo.DBridge.Discord.Broadcaster.responseMinorUpdate(Broadcaster.java:161) ~[?:?]
at uk.co.harieo.DBridge.LinkingCommand.onCommand(LinkingCommand.java:39) ~[?:?]
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[squid-spigot.jar:git-Spigot-4af49dc-c5e9a16]
... 15 more
I have tried moving the methods around, using connection.disconnet() but it always returns this exception. As I've found out, the HttpURLConnection.setFixedLengthStreamingMode() is required for connected to the API I am trying to use or else it returns HTTP Error 411.
Any ideas on how to get this to work?
Thanks for any help in advance
- Harieo

Under your question, just replace connection.getContentLength() with requestData.length.
TL;DR.
When you enter setFixedLengthStreamingMode, you will find out that the connected attribute has been set to true. Well, when is it set to true?
In fact, already connected means you have re-new the HttpURLConnection, which is the root cause.
You should check if you have written some code like this:
connection.getContentType, connection.getContentEncoding
If you do so, please comment them. The implementation of this methods use delegate pattern, which means they will new another HttpURLConnection.

connection.setFixedLengthStreamingMode(connection.getContentLength());
The problem is here. By calling getContentLength() you are committing the request and attempting to read the response, and then you're trying to set the length of the request. It doesn't make sense. The parameter you need to supply is how much data you're going to send, not how much the server is going to send back.
You also need to write something, again before you get the response code or do anything else that implies fetching the response.
As I've found out, the HttpURLConnection.setFixedLengthStreamingMode() is required for connected to the API I am trying to use or else it returns HTTP Error 411.
I don't see how you can tell with this code. All you've done by adding setFixedLengthStreamingMode() is change the error. More likely the problem was that you didn't send anything.
NB You need to set the request method to PUT after calling setDoOutput(true), because that sets it to POST.

Related

what could be the reason for a file on mapped network drive not being seen by java?

My code is:
File file = new File( "T:\\sub1\\15a12f0103135510.jpg");
long lastModified = file.lastModified();
System.out.println( "last modified: " + lastModified);
System.out.println( "done: " + file.exists());
Last modified returns 0. file.exists returns false. However, I can access and open the file through windows explorer, no problem. Accessing the network share directly doesn't work either (in code). Tried smb - shows errors too. I am the admin user on the machine. What could possibly be the reason? what can I check?
if I do the following:
URL url = new URL( "file://host/share/sub1/15a12f0103135510.jpg");
url.openStream();
I get the following error:
java.io.IOException: sun.net.ftp.FtpProtocolException: Welcome message: 501 Proxy unable to contact ftp server
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:308)
at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:400)
at java.net.URL.openStream(URL.java:1045)
at apiteest.ApiTest.main(ApiTest.java:24)
Caused by: sun.net.ftp.FtpProtocolException: Welcome message: 501 Proxy unable to contact ftp server
at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1022)
at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1005)
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:294)
... 3 more
Suppressed: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at sun.net.ftp.impl.FtpClient.readServerResponse(FtpClient.java:420)
at sun.net.ftp.impl.FtpClient.readReply(FtpClient.java:497)
at sun.net.ftp.impl.FtpClient.issueCommand(FtpClient.java:539)
at sun.net.ftp.impl.FtpClient.close(FtpClient.java:1131)
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:303)
... 3 more
Exception in thread "main" java.io.IOException: sun.net.ftp.FtpProtocolException: Welcome message: 501 Proxy unable to c
ontact ftp server
Update:
the code works when executed from powershell but not when executed from powershell started as administrator (the same user though). it also doesn't work from a service, even though the service runs under the same user. Why is it so? And how to enable the share (and possibly the mapped drive) for the service?

com.google.gdata.util.PreconditionFailedException on ListEntry.update() in Google Docs Java API

I have an application which manipulates the rows of a google spreadsheet. Occasionally, when I call ListEntry.update(), I receive the following stack trace:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: com.google.gdata.util.PreconditionFailedException: Precondition Failed
Mismatch: etags = ["E10QemAgYit7ImA-CEFaShYM"], version = [2ag9hk74om621l]
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:614)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.update(Service.java:1563)
at com.google.gdata.client.Service.update(Service.java:1530)
at com.google.gdata.client.GoogleService.update(GoogleService.java:597)
at com.google.gdata.data.BaseEntry.update(BaseEntry.java:639)
at feedProcessor.ProcessClientFeed.UpdateRow(ProcessClientFeed.java:466)
at feedProcessor.ProcessClientFeed.updateGoogleSpreadsheet(ProcessClientFeed.java:404)
at feedProcessor.ProcessClientFeed.processFeed(ProcessClientFeed.java:318)
at feedProcessor.ProcessClientFeed.main(ProcessClientFeed.java:61)
... 5 more
Here is the relevant documentation:
https://developers.google.com/gdata/javadoc/com/google/gdata/data/spreadsheet/ListEntry
https://developers.google.com/gdata/javadoc/com/google/gdata/data/BaseEntry#update()
According to these docs, the update() function is not even capable of throwing a PreconditionFailedException, so the docs are essentially useless here. Testing the issue has shown that this exception is thrown when you try to call the update() function on the same row more than once in a session. Exactly what defines a 'session' is still unclear, but if you loop through all your rows more than once, and call update() on each row in each iteration, you will get this error. The only resolution I am aware of is to write your software such that each row (ListEntry) has update() called only once.
The problem is caused by Google Spreadsheet API Resource Versioning mecanism.
To be able to edit the entry no matter what - just use:
entry.setEtag("*")
before update.
And yes, this is not multi-user friendly. Refetch the feed if you need multi-user support.

The response could not be parsed

I am using redstone-xmlrpc-1.1.1 api with my code and getting this error:
redstone.xmlrpc.XmlRpcException: The response could not be parsed.
at redstone.xmlrpc.XmlRpcClient.handleResponse(Unknown Source)
at redstone.xmlrpc.XmlRpcClient.endCall(Unknown Source)
at redstone.xmlrpc.XmlRpcClient.invoke(Unknown Source)
at redstone.xmlrpc.XmlRpcProxy.invoke(Unknown Source)
at net.bican.wordpress.$Proxy1.newMediaObject(Unknown Source)
at net.bican.wordpress.Wordpress.newMediaObject(Wordpress.java:582)
at WordpressPost.DataWordpressPost.DataPost(DataWordpressPost.java:53)
at arrestcentral.ArrestData.readPdf(ArrestData.java:420)
at arrestcentral.ArrestData.main(ArrestData.java:447)
Caused by: java.io.FileNotFoundException: http://www.arrestcentral.com/XMLrpc.php?
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1478)
... 9 more
can anyone help me why I am unable to post on wordpress..
Well, the exception tells you what's happened - you've tried to fetch a URL of
http://www.arrestcentral.com/XMLrpc.php?
... and it was giving you an HTTP 404 (not found) error. You probably need to change the URL, but you should have more idea of what that URL should be than we do.
java.io.FileNotFoundException: http://www.arrestcentral.com/XMLrpc.php? should have given you a clue:
Nothing was found at the URL you specified. This means that the server returned a HTTP response with the error code 404.
You either mistyped the URL or it no longer exists (at this location).

How do I handle HTTP error codes in an Axis 1 client

We're running an Axis 1 Java client. The web service will sometime return an HTTP error code 500 along with some meaningless HTML body content. In such cases, we get a
javax.xml.soap.SOAPException: org.xml.sax.SAXParseException: Content is not allowed in prolog. at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:796)
I'm certain there's an easy way to catch HTTP errors such that no class attempts to read the SOAP envelope, but I haven't been able to find the right terms to google.
How do I configure Axis (client-config.wsdd) or which handlers do I need to implement so that a webservice reply with an HTTP error code >= 400 can be properly handled?
Thanks
Simon
The cause is in Axis itself.
org.apache.axis.transport.http.HTTPSender#readFromSocket()
will log (level debug)
log.debug(outMsg.getSOAPEnvelope().toString());
If there is no valid SOAP envelope, that call causes the stacktrace above.
Simon

xSocket ExtendedClosedChannelException

I have an error that I sometimes met. The error stack trace is below;
2011-05-04-xWorkerPool-1-thread-2--FATAL-su.games.engine.communication.gameSocketDataHandler:ServiceSocketDataHandler.onData:
could not write. channel is close or not initialized (id=25c1031512fb560155a71db6548S1517c (closed))-----
org.xsocket.connection.ExtendedClosedChannelException: could not write. channel is close or not initialized (id=25c1031512fb560155a71db6548S1517c (closed))
at org.xsocket.connection.AbstractNonBlockingStream.ensureStreamIsOpenAndWritable(AbstractNonBlockingStream.java:1537)
at org.xsocket.connection.AbstractNonBlockingStream.write(AbstractNonBlockingStream.java:1054)
at org.xsocket.connection.AbstractNonBlockingStream.write(AbstractNonBlockingStream.java:1039)
at su.games.engine.communication.ServiceSocketDataHandler.onData(ServiceSocketDataHandler.java:63)
at org.xsocket.connection.HandlerAdapter.performOnData(HandlerAdapter.java:242)
at org.xsocket.connection.HandlerAdapter.access$200(HandlerAdapter.java:42)
at org.xsocket.connection.HandlerAdapter$PerformOnDataTask.run(HandlerAdapter.java:210)
at org.xsocket.SerializedTaskQueue.performPendingTasks(SerializedTaskQueue.java:161)
at org.xsocket.SerializedTaskQueue.access$100(SerializedTaskQueue.java:40)
at org.xsocket.SerializedTaskQueue$MultithreadedTaskProcessor.run(SerializedTaskQueue.java:189)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I use the xSocket 2.8.15 version(jar). Sorry for the tag I have permission issue to create a new tag.The error can be defined as follows. I have number of INonBlockingConnection object and when I try to write some data by using the nbc.write() I get an error as defined above. I search the google and visit the xSocket mailing list. But I can not find any solution. I need some help. Thanks the site StackOverflow and help sorry for the English. I am waiting your advice.
KingSpeech.
The error appears fairly self explanatory. It appears that your connection has been closed or failed to connect. This is most likely due to a problem on the other side (or your network)

Categories

Resources