upload delete list

package MDM.SharePoint; 
 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.PrintWriter; 
import java.net.HttpURLConnection; 
import java.net.URI; 
import java.net.URISyntaxException; 
import java.net.URL; 
import java.rmi.RemoteException; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
 
import javax.activation.DataHandler; 
import javax.activation.FileDataSource; 
import javax.xml.namespace.QName; 
import javax.xml.stream.XMLStreamException; 
 
import org.apache.axiom.om.OMAbstractFactory; 
import org.apache.axiom.om.OMElement; 
import org.apache.axiom.om.OMFactory; 
import org.apache.axiom.om.OMNamespace; 
import org.apache.axiom.om.impl.llom.OMElementImpl; 
import org.apache.axis2.AxisFault; 
import org.apache.axis2.client.Options; 
import org.apache.axis2.transport.http.HTTPConstants; 
import org.apache.axis2.transport.http.HttpTransportProperties; 
import org.apache.commons.httpclient.auth.AuthPolicy; 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.xml.sax.SAXException; 
 
import MDM.SharePoint.CopyStub.DestinationUrlCollection; 
import MDM.SharePoint.CopyStub.FieldInformation; 
import MDM.SharePoint.CopyStub.FieldInformationCollection; 
import MDM.SharePoint.ListsStub.GetListItems; 
import MDM.SharePoint.ListsStub.GetListItemsResponse; 
import MDM.SharePoint.ListsStub.Query_type0; 
import MDM.SharePoint.ListsStub.UpdateListItems; 
import MDM.SharePoint.ListsStub.UpdateListItemsResponse; 
import MDM.SharePoint.ListsStub.Updates_type1; 
import MDM.web.FileInfoBean; 
 
/**
 * 
 * @author jmiao011
 */ 
public class TestUploadFile { 
     
    private static Log logger = LogFactory.getLog(TestSoap.class);   
 
    private String username = "jmiao011"; 
    private String password = "183628at<>1"; 
    private String password1 = "183628at<>1"; 
     
    /**
     * 
     * @param args
     */ 
    public static void main(String[] args){ 
        TestUploadFile test = new TestUploadFile(); 
         
        try { 
            File file = new File("C:/backup/UploadImage.jpg"); 
            test.testcopyIntoItems(file, "UploadImage.jpg"); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
         
//      test.getFilesOfList("123456789"); 
         
//      test.deleteFileOfList("123456789", "UploadImage.jpg"); 
    } 
     
    /**
     * Set authority configuration.
     * @param copyStub
     */ 
    public void setOptions(Options options){         
        // Get the cookie string of certain username and password. 
        String cookieStr = this.getLoginCookie(); 
         
        // Set the authority parameters. 
        HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator(); 
        auth.setUsername(username); 
        auth.setPassword(password); 
        List authPrefs = new ArrayList(1); 
        authPrefs.add(AuthPolicy.NTLM); 
        auth.setAuthSchemes(authPrefs); 
         
        options.setProperty(HTTPConstants.AUTHENTICATE, auth); 
        options.setManageSession(true); 
        options.setProperty(HTTPConstants.COOKIE_STRING, cookieStr); 
    } 
     
    /**
     * Get the files of one list.
     * @param listName
     */ 
    public List<FileInfoBean> getFilesOfList(String listName){ 
         
        ListsStub lists = null; 
        try { 
            lists = new ListsStub(); 
        } catch (AxisFault e1) { 
            e1.printStackTrace(); 
        } 
         
        this.setOptions(lists._getServiceClient().getOptions()); 
         
        // GetListItems 
        GetListItems GetListItemsReq = new GetListItems(); 
        GetListItemsResponse GetListItemsResp = new GetListItemsResponse(); 
        GetListItemsReq.setListName(listName); 
        GetListItemsReq.setViewName(null); 
        Query_type0 param = new Query_type0(); 
//      OMElement eleParam = null; //new OMElement(); 
//      param.setExtraElement(eleParam); 
//      GetListItemsReq.setQuery(param); 
//      GetListItemsReq.setQuery(param); 
        try { 
            GetListItemsResp = lists.GetListItems(GetListItemsReq); 
        } catch (RemoteException e) { 
            e.printStackTrace(); 
        } 
         
        List<FileInfoBean> fileList = new ArrayList<FileInfoBean>(); 
        Iterator iter = GetListItemsResp.getGetListItemsResult().getExtraElement().getChildElements(); 
        while(iter.hasNext()){ 
            OMElementImpl element = (OMElementImpl)iter.next(); 
            Iterator iter1 = element.getChildElements(); 
            while(iter1.hasNext()){ 
                OMElementImpl element1 = (OMElementImpl)iter1.next(); 
//              System.out.println(element1.toString()); 
//              System.out.println(element1.getLineNumber()); 
//              System.out.println(element1.getLocalName()); 
                QName qname = new QName("ows_LinkFilename"); 
                String fileName = element1.getAttributeValue(qname); 
                System.out.println(fileName); 
                String hrefStr = "http://sinw069070:23456/123456789/" + fileName; 
                 
                FileInfoBean fileBean = new FileInfoBean(); 
                fileBean.setHrefStr(hrefStr); 
                fileBean.setFileName(fileName); 
                fileList.add(fileBean); 
            } 
        } 
         
        return fileList; 
    } 
     
    /**
     * Upload a file to certain directory of SharePoint server.
     * @throws java.lang.Exception
     */ 
    public void testcopyIntoItems(File file, String fileName) throws java.lang.Exception { 
        CopyStub copyStub = new CopyStub();//the default implementation should point to the right endpoint 
        //stub._getServiceClient().setTargetEPR(getEndpointReference()); 
 
        this.setOptions(copyStub._getServiceClient().getOptions()); 
 
        CopyStub.CopyIntoItems copyIntoItemsRequest = new CopyStub.CopyIntoItems(); 
 
        DestinationUrlCollection destUrlCollection = new DestinationUrlCollection(); 
        // Destination URL should be an absolute URL. 
        String docUriSharePointDest = "http://sinw069070:23456/Shared Documents/UploadByJava.txt"; 
        String docUriSharePointDest1 = "http://sinw069070:23456/123456789/" + fileName; 
        destUrlCollection.addString(docUriSharePointDest1); 
        copyIntoItemsRequest.setDestinationUrls(destUrlCollection); 
        // Set the source URI. 
        copyIntoItemsRequest.setSourceUrl(fileName); 
 
        try 
        { 
            // Set the source file stream. 
//            File file = new File(sourceFileUrl); 
            Date lastModifiedDate = new Date(); 
            lastModifiedDate.setTime(file.lastModified()); 
            FileDataSource fileDataSource = new FileDataSource(file); 
            DataHandler dataHandler = new DataHandler(fileDataSource); 
 
            copyIntoItemsRequest.setStream(dataHandler); 
 
            // An empty array needs to be created in order to prevent the error: 
            // ErrorCode='Unknown', ErrorMessage='Object reference not set to an instance of an object.' 
            FieldInformationCollection fic = new FieldInformationCollection(); 
            fic.setFieldInformation(new FieldInformation[0]); 
            copyIntoItemsRequest.setFields(fic); 
 
            // Execute the upload operation. 
            CopyStub.CopyIntoItemsResponse copyIntoItemsResponse = copyStub.CopyIntoItems(copyIntoItemsRequest); 
            System.out.println("GetCopyIntoItems(): " + copyIntoItemsResponse.localResultsTracker); 
 
            // Get the root element of the response 
            OMElement root = copyIntoItemsResponse.getOMElement(copyIntoItemsResponse.MY_QNAME, OMAbstractFactory.getOMFactory()); 
 
            // Log the response data using the root element 
            StringBuilder sb = new StringBuilder(1000); 
            //displayXml(root, sb, 0); 
            System.out.println(sb.toString()); 
        } catch (Throwable t) { 
            t.getCause().printStackTrace(); 
        } finally { 
            copyStub.cleanup(); 
        } 
    } 
     
    /**
     * Delete one file from one file list.
     * @param fileName
     */ 
    public void deleteFileOfList(String listName, String fileName){ 
        // New instance of ListsStub. 
        ListsStub lists = null; 
        try { 
            lists = new ListsStub(); 
        } catch (AxisFault e1) { 
            e1.printStackTrace(); 
        } 
         
        // Set authority options. 
        this.setOptions(lists._getServiceClient().getOptions()); 
         
        UpdateListItems updateItemsReq = new UpdateListItems(); 
        updateItemsReq.setListName(listName); 
        Updates_type1 deleteType = new Updates_type1(); 
        /** Set the Updates block Start.*/ 
        OMFactory fac = OMAbstractFactory.getOMFactory(); 
        OMNamespace omNs = fac.createOMNamespace("", ""); 
        OMElement deleteParam = fac.createOMElement(new QName("Batch")); 
        OMElement method = fac.createOMElement("Method", omNs); 
        method.addAttribute("ID", "1", omNs); 
        method.addAttribute("Cmd", "Delete", omNs); 
        OMElement field_Name = fac.createOMElement(new QName("Field")); 
        field_Name.addAttribute("Name", "ID", omNs); 
        method.addChild(field_Name); 
        OMElement field_FileRef = fac.createOMElement(new QName("Field")); 
        field_FileRef.addAttribute("Name", "FileRef", omNs); 
        field_FileRef.setText("http://sinw069070:23456/123456789/" + fileName); 
        method.addChild(field_FileRef); 
        deleteParam.addChild(method); 
        System.out.println("Text: " + deleteParam.getText()); 
        System.out.println("Is Complete: " + deleteParam.isComplete()); 
        try { 
            System.out.println("toStringWithConsume: " + deleteParam.toStringWithConsume()); 
        } catch (XMLStreamException e1) { 
            e1.printStackTrace(); 
        } 
        /** Set the Updates block End.*/ 
        deleteType.setExtraElement(deleteParam); 
        updateItemsReq.setUpdates(deleteType); 
         
        try { 
            UpdateListItemsResponse response = lists.UpdateListItems(updateItemsReq); 
            Object obj = response.localUpdateListItemsResult.getExtraElement().getFirstElement().getFirstElement().getText(); 
            if("0x00000000".equals(obj.toString())){ 
                System.out.println("Error code is: " + obj.toString() + ", deleted successfully."); 
            }else{ 
                System.out.println("Error occured when deleting."); 
            } 
        } catch (RemoteException e) { 
            e.printStackTrace(); 
        } 
    }/**这里下载返回的是InputStream,注释的部分是用来写到本地。*/ 
    public InputStream download(String operFileName) throws Exception { 
        String fileUrl = "http://sinw069070:23456/123456789/" + operFileName; 
         
        URL url = new URL(fileUrl); 
        String baseUrl = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort(); 
        String filePath = url.getPath(); 
 
        DefaultHttpClient httpclient = new DefaultHttpClient(); 
        HttpEntity entity = null; 
        InputStream inStream = null; 
        FileOutputStream fileOutputStream = null; 
        String tempFileName = null; 
        String tempFileUrl = null; 
        try { 
            TestUploadFile testTool = new TestUploadFile(); 
            String cookie = testTool.getLoginCookie(); 
             
            HttpGet httpget = new HttpGet(fileUrl); 
            httpget.setHeader("cookie", cookie); 
 
            // Create a response handler 
            httpclient.getCredentialsProvider().setCredentials( 
                    new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_SCHEME), 
                    new UsernamePasswordCredentials(username, password)); 
            HttpResponse response = httpclient.execute(httpget); 
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 
                throw new IOException(response.getStatusLine().toString()); 
            } 
 
            // Get the file input stream. 
            entity = response.getEntity(); 
            inStream = entity.getContent(); 
             
//          Date date = new Date(); 
//          long dateLong = date.getTime(); 
//          tempFileName = dateLong + "_" + operFileName; 
//          System.out.println("tempFileName: " + tempFileName); 
//          tempFileUrl = "C:/backup/" + tempFileName; 
//          fileOutputStream = new FileOutputStream(tempFileUrl); 
//          int b; 
//          while ((b = inStream.read()) != -1) { 
//              fileOutputStream.write(b); 
//          } 
             
            System.out.println("Download file successfully."); 
        }catch(Exception e){ 
            e.printStackTrace(); 
        }finally { 
            // When HttpClient instance is no longer needed, 
            // shut down the connection manager to ensure 
            // immediate deallocation of all system resources 
//           if(inStream!=null) inStream.close(); 
//           if(fileOutputStream!=null) fileOutputStream.close(); 
//             httpclient.getConnectionManager().shutdown(); 
        } 
         
        return inStream; 
    } 
     
    /**我测试的SharePoint Server使用的Forms登录验证方式,Java访问首先要提供登录cookie,因此每次交互前都重新获取下cookie字符串。因为在Authentication的login方法中得不到cookie字符串(MSDN上提供的方法中能直接获取到,我也没搞明白是什么原因,只能单独获取一下,希望知道的朋友能给我留言)。
     * Get the cookie string of one username and password when login.
     * @return
     * @throws URISyntaxException
     * @throws IOException
     * @throws SAXException
     */ 
    public String getLoginCookie() { 
        String cookieStr = null; 
        HttpURLConnection httpUrlConnection = null; 
        OutputStream os = null; 
        PrintWriter out = null; 
        StringBuilder sb = null; 
         
        try{ 
            // soap request string   
            final String soapReuqest =  
              "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soap=\"http://schemas.microsoft.com/sharepoint/soap/\">"  
              + "<soapenv:Header/>" 
              + "<soapenv:Body>" 
              + "<soap:Login>" 
              + "<soap:username>" + username + "</soap:username>" 
              + "<soap:password>" + password1 + "</soap:password>" 
              + "</soap:Login>" 
              + "</soapenv:Body>" 
              + "</soapenv:Envelope>";   
               
            // Web 服务所在的地址   
            URI uri = new URI("http://sinw069070:23456/_vti_bin/Authentication.asmx");   
            URL url = uri.toURL();   
               
            // 打开连接   
            httpUrlConnection = (HttpURLConnection) url.openConnection(); 
             
            // 可读取   
            httpUrlConnection.setDoInput(true);   
            httpUrlConnection.setDoOutput(true);   
            httpUrlConnection.setRequestMethod("POST");   
               
            // set request header   
            httpUrlConnection.setRequestProperty("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/Login");   
            httpUrlConnection.setRequestProperty("Content-type", "text/xml;charset=UTF-8");   
             
            os = httpUrlConnection.getOutputStream();   
            out = new PrintWriter(os);   
            out.println(soapReuqest);   
            out.flush();   
             
             
             
            // http status ok   
            sb = new StringBuilder();   
            if (HttpURLConnection.HTTP_OK == httpUrlConnection.getResponseCode())   
            {   
                if (logger.isDebugEnabled())  logger.debug("HTTP_OK");   
                 
                Map map1 = httpUrlConnection.getHeaderFields(); 
                cookieStr = httpUrlConnection.getHeaderField("Set-Cookie"); 
                System.out.println("cookieStr: " + cookieStr); 
                 
                InputStream is = httpUrlConnection.getInputStream();   
                BufferedReader br = new BufferedReader(new InputStreamReader(is));   
                for (String line = br.readLine(); line != null; line = br.readLine()){   
                    sb.append(line);   
                }   
                is.close(); 
            }else{ 
                System.out.println(httpUrlConnection.getResponseCode() + ": " + httpUrlConnection.getResponseMessage()); 
            } 
        }catch (URISyntaxException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }finally{ 
            // Release resource   
            try { 
                if(os!=null) os.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
            if(out!=null) out.close(); 
            if(httpUrlConnection!=null) httpUrlConnection.disconnect();   
        } 
           
         
        String soapResponse = sb.toString();   
        return cookieStr; 
    } 
     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值