While trying to ftp (with implicit ssl) a file to a server, I consistently get a 'Connection Reset By Peer: Socket Write Error' or abnormally a 'Connection Aborted By Software' error. The file is uploaded to the server, but is completely empty. However, after setting up a local test ftp server, I upload files to that server with no issue. Could these errors be cause by some type of firewall? If not, is there another issue. If it is, can anything in the code be changed to fix it?
Using Apache Commons:
String SFTPHOST = compParam.getSftpHostNme();
int SFTPPORT = 990;
String SFTPUSER = compParam.getSftpLogin();
String SFTPPASS = compParam.getSftpPassword();
FTPSClient ftpClient = new FTPSClient(true);
try {
ftpClient.connect(SFTPHOST, SFTPPORT);
if(!ftpClient.login(SFTPUSER, SFTPPASS)){
SwingUtils.showMessage(this, "Error: Trouble Connecting \n" + "User Name and Password or Host is incorrect \n"
+ "or someone else is using these credentials");
return;
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
File f = new File(TLCTripRecordExportDlg.filePath + TLCTripRecordExportDlg.fileName);
String remoteFile = TLCTripRecordExportDlg.fileName;
FileInputStream inputStream = new FileInputStream(f);
ProgressMonitorInputStream pmiStream = new ProgressMonitorInputStream(this,"Uploading the File",inputStream);
// OutputStream os = ftpClient.storeFileStream(remoteFile);
// byte[] buffer = new byte[1024];
// int len;
// while ((len = pmiStream.read(buffer)) != -1)
// {
// os.write(buffer, 0, len);
// os.flush();
// }
// pmiStream.close();
// os.close();
if(ftpClient.storeFile(remoteFile, pmiStream)){
inputStream.close();
pmiStream.close();
}else{
SwingUtils.showMessage(this, "File Not Uploaded: " + ftpClient.getReplyString());
return;
}
The error is thrown at store file. Here's the stack trace:
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at java.io.FilterOutputStream.flush(FilterOutputStream.java:123)
at java.io.FilterOutputStream.flush(FilterOutputStream.java:123)
at com.limosys.gui.job.TLCTripUploadDlg.upload_actionPerformed(TLCTripUploadDlg.java:261)
at com.limosys.gui.job.TLCTripUploadDlg$3.actionPerformed(TLCTripUploadDlg.java:193)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6290)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6055)
at java.awt.Container.processEvent(Container.java:2039)
at java.awt.Component.dispatchEventImpl(Component.java:4653)
at java.awt.Container.dispatchEventImpl(Container.java:2097)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
at java.awt.Container.dispatchEventImpl(Container.java:2083)
at java.awt.Window.dispatchEventImpl(Window.java:2482)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:648)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:607)
at java.awt.EventQueue$1.run(EventQueue.java:605)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:621)
at java.awt.EventQueue$2.run(EventQueue.java:619)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:618)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
at java.awt.Dialog$1.run(Dialog.java:1044)
at java.awt.Dialog$3.run(Dialog.java:1096)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Dialog.show(Dialog.java:1094)
at java.awt.Component.show(Component.java:1584)
at java.awt.Component.setVisible(Component.java:1536)
at java.awt.Window.setVisible(Window.java:841)
at java.awt.Dialog.setVisible(Dialog.java:984)
at com.limosys.gui.dialogs.gen.GenDialog.setVisible(GenDialog.java:250)
at com.limosys.gui.job.TLCTripUploadDlg.showIt(TLCTripUploadDlg.java:325)
at com.limosys.gui.job.TLCTripExport$ExportTLCTripTask.invoke(TLCTripExport.java:363)
at com.limosys.dblib.utils.JLimoWorker$1.run(JLimoWorker.java:169)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:646)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:607)
at java.awt.EventQueue$1.run(EventQueue.java:605)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:616)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
I found the answer. Add these two lines:
ftpClient.execPROT("P");
ftpClient.execPBSZ(0);
Related
I am getting a "The session id is not valid." exception when reading the value of a node ,but just sometimes,I konw the session is not timeout,so why?
the exception :
java.util.concurrent.ExecutionException: UaServiceFaultException: status=Bad_SessionIdInvalid, message=The session id is not valid.
at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
at com.ggnykj.smartems.cloud.server.autocontrol.client.OpcClientServer.readNode(OpcClientServer.java:230)
at com.ggnykj.smartems.cloud.server.autocontrol.controller.OpcClientServerController.readNode(OpcClientServerController.java:115)
at com.ggnykj.smartems.cloud.server.autocontrol.server.SaveExOpcData.run(SaveExOpcData.java:59)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: UaServiceFaultException: status=Bad_SessionIdInvalid, message=The session id is not valid.
at org.eclipse.milo.opcua.stack.client.UaTcpStackClient.lambda$receiveResponse$16(UaTcpStackClient.java:367)
at org.eclipse.milo.opcua.stack.core.util.ExecutionQueue$PollAndExecute.run(ExecutionQueue.java:107)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
... 3 more
Exception in thread "pool-2-thread-2" java.lang.NullPointerException
at com.ggnykj.smartems.cloud.server.autocontrol.controller.OpcClientServerController.readNode(OpcClientServerController.java:116)
at com.ggnykj.smartems.cloud.server.autocontrol.server.SaveExOpcData.run(SaveExOpcData.java:59)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
there is my code:
MyX509IdentityProvider x509IdentityProvider = new MyX509IdentityProvider(clientOption.opcServer.getCertFilePath(),
clientOption.opcServer.getPrivateKeyPath());
X509Certificate cert = x509IdentityProvider.getCertificate();
KeyPair keyPair = new KeyPair(cert.getPublicKey(), x509IdentityProvider.getPrivateKey());
OpcUaClientConfig config = OpcUaClientConfig.builder()
.setApplicationName(LocalizedText.english(clientOption.opcServer.getOpcServerName()))
//.setApplicationUri("urn:eclipse:milo:examples:client")
.setApplicationUri("")
//.setCertificate(loader.getClientCertificate())
//.setKeyPair(loader.getClientKeyPair())
.setCertificate(cert)
.setKeyPair(keyPair)
.setEndpoint(endpoint)
.setIdentityProvider(clientOption.getIdentityProvider())
.setChannelLifetime(uint(600000000))
.setSessionTimeout(uint(600000000))
//.setRequestTimeout(uint(5000))
.build();
return new OpcUaClient(config);
there is the connect and read code:
private OpcUaClient getOpcClient(OpcServer opcServer){
OpcUaClient client = null;
if(null!=opcClientMap.get(opcServer.getOpcServerId())){
client = opcClientMap.get(opcServer.getOpcServerId());
}else{
try {
ClientOption clientOption = new ClientOption(opcServer);
client = new ClientOptionRunner(clientOption).createClient();
}catch (Throwable t){
logger.error("Error getting client: {}", t.getMessage(), t);
}
opcClientMap.put(opcServer.getOpcServerId(),client);
}
return client;
}
public DataValue readNode(OpcServer opcServer,NodeId nodeId){
OpcUaClient client = getOpcClient(opcServer);
DataValue value = null;
try {
client.connect().get();
value = client.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
}catch (Exception e){
e.printStackTrace();
}
return value;
}
when I read the node,there is the problem:
value = client.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
but I don't know why
This StatusCode comes from the server.
Maybe you can capture this behavior on Wireshark to ensure you're really using the same OpcUaClient instance you think you are and not one that has had its session timeout somehow. Or maybe the capture will show the server is at fault and returning this StatusCode when you read on a freshly created Session.
I am trying to connect to Hive on EMR through Eclipse, but I get an error.
Exception in thread "main" java.sql.SQLException: Could not open client transport with JDBC Uri: jdbc:hive2://localhost:8158: java.net.ConnectException: Connection refused
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:215)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:163)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.readypulse.sparkanalytics.HiveQLConnector.<init>(HiveQLConnector.java:31)
at com.readypulse.sparkanalytics.HiveQLConnector.main(HiveQLConnector.java:83)
Caused by: org.apache.thrift.transport.TTransportException: java.net.ConnectException: Connection refused
You would need a SSH Tunnel to poke a hole to EMR master. And then connect via JDBC.
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
private static String hiveConnectionString = "jdbc:hive2://localhost:8158";
//Need port forwarding
SparkPortForwarding.portForwardForSpark();
Class c = Class.forName(driverName);
Connection connection = DriverManager.getConnection(hiveConnectionString,
"user", "pwd");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
You can do port forwarding via shell as:
ssh -i ~/mykey.pem -N -L 8158:<maserhost>:10000 hadoop#<masterhost>
Or You can use the code using the library JSch
public static void portForwardForSpark() {
try {
if(session != null && session.isConnected()) {
return;
}
JSch jsch = new JSch();
jsch.addIdentity(PATH_TO_SSH_KEY_PEM);
String host = REMOTE_HOST;
session = jsch.getSession(USER, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.connect();
int assingedPort = session.setPortForwardingL(LPORT, RHOST, RPORT);
System.out.println("Port forwarding done for the post : " + assingedPort);
} catch (Exception e) {
System.out.println(e);
}
}
I am trying to send message to my verified phone number, which I see on
and I send it from number that I get from
My code looks like
object TextMessage {
def send() = {
// Create a rest client
val client: TwilioRestClient = new TwilioRestClient("AC*****", "324324234******")
val mainAccount: Account = client.getAccount
val messageFactory: SmsFactory = mainAccount.getSmsFactory
var messageParams: List[NameValuePair] = List[NameValuePair]()
messageParams = messageParams :+ new BasicNameValuePair("To", "MyVerifiedNumber")
messageParams = messageParams :+ new BasicNameValuePair("From", "NumberIGotFromTwilio")
messageParams = messageParams :+ new BasicNameValuePair("Body", "The system crashed just now!")
println(messageParams)
messageFactory.create(ListBuffer(messageParams).flatten)
}
def main(args: Array[String]) {
TextMessage.send()
}
}
When I run, I get the following
Exception in thread "main" com.twilio.sdk.TwilioRestException: The From phone number +1NumberIGotFromTwilio is not a valid, SMS-capable inbound phone number or short code for your account.
at com.twilio.sdk.TwilioRestException.parseResponse(TwilioRestException.java:74)
at com.twilio.sdk.TwilioClient.safeRequest(TwilioClient.java:509)
at com.twilio.sdk.resource.list.SmsList.create(SmsList.java:79)
at com.shn.enterpriseconnector.util.TextMessage$.send(TextMessage.scala:25)
at com.shn.enterpriseconnector.util.TextMessage$.main(TextMessage.scala:29)
at com.shn.enterpriseconnector.util.TextMessage.main(TextMessage.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
I'm trying to deploy my jsp site on Oracle web server, but when I call my web service using a port I get the following error :
SEVERE: SAAJ0120: Can't add a header when one is already present
This is the code for my HeaderHandler
public boolean handleMessage(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
SOAPMessage message = smc.getMessage();
SOAPEnvelope envelope = null;
SOAPHeader header = null;
try {
envelope = smc.getMessage().getSOAPPart().getEnvelope();
header = envelope.addHeader();
SOAPElement security =
header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
//http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd
SOAPElement BinarySecurityToken =
security.addChildElement("BinarySecurityToken", "wsse");
BinarySecurityToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
//EncodingType="SSHA" ValueType="AccessManagerSSOSecurityToken" wsu:Id="OAMToken"
BinarySecurityToken.addAttribute(new QName("EncodingType"), "SSHA");
BinarySecurityToken.addAttribute(new QName("ValueType"), "AccessManagerSSOSecurityToken");
BinarySecurityToken.addAttribute(new QName("wsu:Id"), "OAMToken");
BinarySecurityToken.addTextNode(token);
//message.writeTo(System.out);
//System.out.println("");
} catch (Exception e) {
try {
header = envelope.addHeader();
} catch (SOAPException e1) {
e1.printStackTrace();
}
//e.printStackTrace();
}
} else {
try {
//This handler does nothing with the response from the Web Service so
//we just print out the SOAP message.
SOAPMessage message = smc.getMessage();
//message.writeTo(System.out);
//System.out.println("");
} catch (Exception ex) {
ex.printStackTrace();
}
}
return outboundProperty;
}
EDIT:
The error is
com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl addHeader
SEVERE: SAAJ0120: Can't add a header when one is already present
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Can't add a header when one is already present.
at com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl.addHeader(EnvelopeImpl.java:114)
at com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl.addHeader(EnvelopeImpl.java:94)
at com.standardandpoors.wso.HeaderHandler.handleMessage(HeaderHandler.java:33)
at com.standardandpoors.wso.HeaderHandler.handleMessage(HeaderHandler.java:1)
at com.sun.xml.ws.handler.HandlerProcessor.callHandleMessage(HandlerProcessor.java:297)
at com.sun.xml.ws.handler.HandlerProcessor.callHandlersRequest(HandlerProcessor.java:138)
at com.sun.xml.ws.handler.ClientSOAPHandlerTube.callHandlersOnRequest(ClientSOAPHandlerTube.java:144)
at com.sun.xml.ws.handler.HandlerTube.processRequest(HandlerTube.java:115)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:892)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:841)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:804)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:706)
at com.sun.xml.ws.client.Stub.process(Stub.java:385)
at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:189)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:102)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:172)
at $Proxy125.findUserById(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at weblogic.wsee.jaxws.spi.ClientInstanceInvocationHandler.invoke(ClientInstanceInvocationHandler.java:84)
at $Proxy120.findUserById(Unknown Source)
at com.standardandpoors.wso.IdmWSUtil.findUserById(IdmWSUtil.java:44)
at com.standardandpoors.idm.controller.JspRedirectionController.forgotPassword(JspRedirectionController.java:123)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:242)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:216)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:132)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:338)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:221)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3284)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3254)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2163)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2089)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2074)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1513)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
EDIT:
The issue is present using JDK 1.8, not in 1.7
You can replace the header by detaching the old one first.
if (envelope.getHeader() != null) {
envelope.getHeader().detachNode();
}
SOAPHeader header = envelope.addHeader();
http://docs.oracle.com/javaee/5/api/javax/xml/soap/SOAPEnvelope.html
I was finally able to resolve the issue. I just added an if condition to check whether the header was NULL or not, if it was NULL only then I added the header else continued with the program.
This worked for me !
if(header == null){
header = envelope.addHeader();
}
Wouldn't it be easier to just use?
SOAPHeader header = envelope.getHeader();
SOAPHeader header = envelope.getHeader();
if (header == null) {
header = add.addHeader();
}
header.addChildElement(wsSecurityElement);
Is my personal choice: detaching the previous SOAPHeader can break the code, for instance in case of handlers chaining, where other upstream handlers might add their elements to the header.
null testing makes the code backward compatible with previous JREs; otherwise switching from addHeader to getHeader is enough.
I have installed SQL Server 2012 Express in my laptop and tried to run a sample java program as follows:
import java.sql.*;
public class Ex2 {
Connection con;
Statement st;
ResultSet rs;
public Ex2(String query){
System.out.println("IN Const1");
try{
System.out.println("IN try");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String dbName = "HOME";
String user = "sa";
String password = "JUL#2012";
//the name of my SQL SERVER 2005 instance
String SqlServerInstance = "SQLEXPRESS";
String url = "jdbc:jtds:sqlserver://localhost:1433";
url = url + "/" + dbName;
url = url + ";" + SqlServerInstance;
con = DriverManager.getConnection(url, user, password);
System.out.println("nach DriverManager");
st = con.createStatement();
st.executeQuery(query);
rs = st.getResultSet();
while ( rs.next() ){
System.out.println(rs.getString(0));
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
}
catch(Exception e){
e.printStackTrace();
System.out.println("Exception: " + e.getMessage());
}
}
public static void main(String[] argv){
System.out.println("IN MAIN");
Ex2 test = new Ex2("SELECT * FROM HOME.dbo.employee;");
}
}*
and getting the following error log in the console:
java.sql.SQLException: Network error IOException: Connection timed out: connect
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:410)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at Ex2.<init>(Ex2.java:22)
at Ex2.main(Ex2.java:43)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:516)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:307)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:257)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:311)
Exception: Network error IOException: Connection timed out: connect
... 6 more
When I checked the sql server configuration manager the services SQL Server and SQL Server Browser are running.
I have been googling for the last two days and struggle to fix this issue and couldn't. So please help me.