[笔记]写代码遇到的一些问题汇总下

本篇是用来填上一篇 挖下的坑的。

1.java调用webservice

有一些已有的webservice服务,由xfire生成发布,有些有参数,有些无参数,无参数的直接我直接使用org.codehaus.xfire这个包里的Client来动态生成客户端。然后调用就可以了。非常简单

Client client = null;
        try {
            client = new Client(
                    new URL(
                            “http://leaver.me/testService?wsdl"));
            client.invoke(“refreshAllCache”, new Object[0]);

    } catch (MalformedURLException e) {

        e.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();
    }</pre>

但对于有参的,且是服务器自定义的类作为参数的时候,实在是搞不定。。不管是把自定义的类放到本地,包名一致,在invoke的时候生成这个对象还是其他什么方法。都无法完成。

最终换了直接发送soap报文来完成。dirty hack啊。如果你有一些好的方法希望不吝赐教。

解决方案来源自stackoverflow,因为stackoverflow现在国内好像有时候打不开。因此把代码贴过来。有疑问的话留言讨论。

import javax.xml.soap.;
import javax.xml.transform.;
import javax.xml.transform.stream.*;

public class SOAPClientSAAJ {

/**
 * Starting point for the SAAJ - SOAP Client Testing
 */
public static void main(String args[]) {
    try {
        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        // Send SOAP Message to SOAP Server
        String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

        // Process the SOAP Response
        printSOAPResponse(soapResponse);

        soapConnection.close();
    } catch (Exception e) {
        System.err.println("Error occurred while sending SOAP Request to Server");
        e.printStackTrace();
    }
}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    &lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/"&gt;
        &lt;SOAP-ENV:Header/&gt;
        &lt;SOAP-ENV:Body&gt;
            &lt;example:VerifyEmail&gt;
                &lt;example:email&gt;mutantninja@gmail.com&lt;/example:email&gt;
                &lt;example:LicenseKey&gt;123&lt;/example:LicenseKey&gt;
            &lt;/example:VerifyEmail&gt;
        &lt;/SOAP-ENV:Body&gt;
    &lt;/SOAP-ENV:Envelope&gt;
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("mutantninja@gmail.com");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.print("Request SOAP Message = ");
    soapMessage.writeTo(System.out);
    System.out.println();

    return soapMessage;
}

/**
 * Method used to print the SOAP Response
 */
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    Source sourceContent = soapResponse.getSOAPPart().getContent();
    System.out.print("\nResponse SOAP Message = ");
    StreamResult result = new StreamResult(System.out);
    transformer.transform(sourceContent, result);
}

}

2.Access restriction on class due to restriction on required library rt.jar? 报错

总么都感觉是环境问题,系统bug。解决如下:

  1. 进入project properties的 Build Path 设置里.
  2. 移除 JRE System Library
  3. 再添加回来,方法是: 选择 “Add Library” ,然后选择 JRE System Library.  

3.SSHManager类报错:com.jcraft.jsch.JSchException: UnknownHostKey

我使用的一个SSHManager类如下:

package me.leaver.Util;

import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger;

import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session;

public class SSHManager { private static final Logger LOGGER = Logger.getLogger(SSHManager.class .getName()); private JSch jschSSHChannel; private String strUserName; private String strConnectionIP; private int intConnectionPort; private String strPassword; private Session sesConnection; private int intTimeOut;

private void doCommonConstructorActions(String userName, String password,
        String connectionIP, String knownHostsFileName) {
    jschSSHChannel = new JSch();

    try {
        jschSSHChannel.setKnownHosts(knownHostsFileName);
    } catch (JSchException jschX) {
        logError(jschX.getMessage());
    }

    strUserName = userName;
    strPassword = password;
    strConnectionIP = connectionIP;
}

public SSHManager(String userName, String password, String connectionIP,
        String knownHostsFileName) {
    doCommonConstructorActions(userName, password, connectionIP,
            knownHostsFileName);
    intConnectionPort = 22;
    intTimeOut = 60000;
}

public SSHManager(String userName, String password, String connectionIP,
        String knownHostsFileName, int connectionPort) {
    doCommonConstructorActions(userName, password, connectionIP,
            knownHostsFileName);
    intConnectionPort = connectionPort;
    intTimeOut = 60000;
}

public SSHManager(String userName, String password, String connectionIP,
        String knownHostsFileName, int connectionPort,
        int timeOutMilliseconds) {
    doCommonConstructorActions(userName, password, connectionIP,
            knownHostsFileName);
    intConnectionPort = connectionPort;
    intTimeOut = timeOutMilliseconds;
}

public String connect() {
    String errorMessage = null;

    try {
        sesConnection = jschSSHChannel.getSession(strUserName,
                strConnectionIP, intConnectionPort);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        sesConnection.setConfig(config);
        sesConnection.setPassword(strPassword);
        sesConnection.connect(intTimeOut);
    } catch (JSchException jschX) {
        errorMessage = jschX.getMessage();
    }

    return errorMessage;
}

private String logError(String errorMessage) {
    if (errorMessage != null) {
        LOGGER.log(Level.SEVERE, "{0}:{1} - {2}", new Object[] {
                strConnectionIP, intConnectionPort, errorMessage });
    }

    return errorMessage;
}

private String logWarning(String warnMessage) {
    if (warnMessage != null) {
        LOGGER.log(Level.WARNING, "{0}:{1} - {2}", new Object[] {
                strConnectionIP, intConnectionPort, warnMessage });
    }

    return warnMessage;
}

public String sendCommand(String command) {
    StringBuilder outputBuffer = new StringBuilder();

    try {
        Channel channel = sesConnection.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.connect();
        InputStream commandOutput = channel.getInputStream();
        int readByte = commandOutput.read();

        while (readByte != 0xffffffff) {
            outputBuffer.append((char) readByte);
            readByte = commandOutput.read();
        }

        channel.disconnect();
    } catch (IOException ioX) {
        logWarning(ioX.getMessage());
        return null;
    } catch (JSchException jschX) {
        logWarning(jschX.getMessage());
        return null;
    }

    return outputBuffer.toString();
}

public void close() {
    sesConnection.disconnect();
}

}

报这个错是因为
public String connect() {
        String errorMessage = null;

    try {
        sesConnection = jschSSHChannel.getSession(strUserName,
                strConnectionIP, intConnectionPort);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        sesConnection.setConfig(config);
        sesConnection.setPassword(strPassword);
        sesConnection.connect(intTimeOut);
    } catch (JSchException jschX) {
        errorMessage = jschX.getMessage();
    }

    return errorMessage;
}</pre>

连接这段代码里少了config.put(“StrictHostKeyChecking”, “no”);这段设置,这个是去掉了严格的安全检查,一般只用于测试目的。

4.navicat连接oracle数据库

之前使用PL/SQL操作Oracle数据库,使用Heidisql操作mysql数据库。。切换麻烦。而且PL/SQL搜索的时候中文有问题。于是打算使用navicat统一管理

方法是:

1.首先下载Instant Client 的32位版本和Navicat Premium

2.然后解压Instant Client,配置navicat

navicat_oracle

选择oci文件即可

然后新建oracle配置,选择basic模式,其他的根据你的数据库信息自己填写即可。

 

5.HttpClient的logger日志实在太多了

大人,实在太多了。看不过来啊。附赠一篇log4j配置文件详解

在log4j.properties文件中添加如下配置信息

log4j.logger.httpclient.wire.header=INFO

log4j.logger.httpclient.wire.content=INFO

log4j.logger.org.apache.commons.httpclient = INFO

6.其他

最后附赠一些实用的工具

http://www.freeformatter.com/ 程序员必备。各类转换,包括转义工具,格式校验工具。效果很好。

流体力学理论与F1赛车的空气动力学123   什么雷诺数,伯努利方程,文丘里效应,当年木有好好学啊。这么高大上的东西果然还是有压力。

comments powered by Disqus