Project

General

Profile

« Previous | Next » 

Revision 6269

consolidate multi part handling in the super class - subclasses need only call the appropriate helper to get access to the needed resources. superclass does some validation to make sure the files are in place in the request

View differences:

src/edu/ucsb/nceas/metacat/restservice/MNResourceHandler.java
25 25
import java.io.ByteArrayInputStream;
26 26
import java.io.File;
27 27
import java.io.FileInputStream;
28
import java.io.FileNotFoundException;
28 29
import java.io.IOException;
29 30
import java.io.InputStream;
30 31
import java.io.OutputStream;
......
46 47
import javax.servlet.http.HttpServletRequest;
47 48
import javax.servlet.http.HttpServletResponse;
48 49

  
49
import org.apache.commons.fileupload.FileUploadException;
50 50
import org.apache.commons.io.IOUtils;
51 51
import org.apache.log4j.Logger;
52 52
import org.dataone.client.ObjectFormatCache;
......
878 878
        }
879 879
    }
880 880
    
881
    /**
882
     * Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query 
883
     * then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
884
     * 
885
     * NOTE:
886
     *      This is the only method that uses EcoGrid classes for its implementation.  
887
     *      It does so because it takes an EcoGrid Query as input, and outputs an
888
     *      EcoGrid ResultSet document.  These documents are parsed by the auto-generated
889
     *      EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
890
     *      This creates a circular dependency, because the Metacat classes are needed
891
     *      to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
892
     *      method.  This circularity could be resolved by moving the EcoGrid classes
893
     *      to Metacat directly.  As we transition away from EcoGrid SOAP methods in
894
     *      favor of these REST interfaces, this circular dependency can be eliminated.
895
     *        
896
     * @throws Exception
897
     */
898
    private void query() throws Exception {
899
        /*  This block commented out because of the EcoGrid circular dependency.
900
         *  For now, query will not be supported until the circularity can be
901
         *  resolved, probably by moving the ecogrid query syntax transformers
902
         *  directly into the Metacat codebase.  MBJ 2010-02-03
903
         
904
        try {
905
            EcogridQueryParser parser = new EcogridQueryParser(request
906
                    .getReader());
907
            parser.parseXML();
908
            QueryType queryType = parser.getEcogridQuery();
909
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
910
                new EcogridJavaToMetacatJavaQueryTransformer();
911
            QuerySpecification metacatQuery = queryTransformer
912
                    .transform(queryType);
913

  
914
            DBQuery metacat = new DBQuery();
915

  
916
            boolean useXMLIndex = (new Boolean(PropertyService
917
                    .getProperty("database.usexmlindex"))).booleanValue();
918
            String xmlquery = "query"; // we don't care the query in resultset,
919
            // the query can be anything
920
            PrintWriter out = null; // we don't want metacat result, so set out null
921

  
922
            // parameter: queryspecification, user, group, usingIndexOrNot
923
            StringBuffer result = metacat.createResultDocument(xmlquery,
924
                    metacatQuery, out, username, groupNames, useXMLIndex);
925

  
926
            // create result set transfer       
927
            String saxparser = PropertyService.getProperty("xml.saxparser");
928
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
929
                    new StringReader(result.toString()), saxparser, queryType
930
                            .getNamespace().get_value());
931
            ResultsetType records = metacatResultsetParser.getEcogridResult();
932

  
933
            System.out
934
                    .println(EcogridResultsetTransformer.toXMLString(records));
935
            response.setContentType("text/xml");
936
            out = response.getWriter();
937
            out.print(EcogridResultsetTransformer.toXMLString(records));
938

  
939
        } catch (Exception e) {
940
            e.printStackTrace();
941
        }*/
942
        response.setContentType("text/xml");
943
        response.setStatus(501);
944
        PrintWriter out = response.getWriter();
945
        out.print("<error>Query operation not yet supported by Metacat.</error>");
946
        out.close();
947
    }
948 881
    
949 882
    /**
950
     * return a tmp file with a given name
951
     * @param name
952
     * @return
953
     */
954
    private static File getTempFile(String name)
955
    {
956
        File tmpDir = getTempDirectory();
957
        File f = new File(tmpDir, name);
958
        return f;
959
    }
960
    
961
    /**
962
     * return a temp file with a default name
963
     * @return
964
     */
965
    private static File getTempFile()
966
    {
967
        return getTempFile(new Date().getTime() + ".tmp");
968
    }
969
    
970
    /**
971 883
     * Inserts or updates the object
972 884
     * 
973 885
     * @param guid - ID of data object to be inserted or updated.  If action is update, the pid
974 886
     *               is the existing pid.  If insert, the pid is the new one
887
     * @throws InvalidRequest 
888
     * @throws ServiceFailure 
889
     * @throws FileNotFoundException 
890
     * @throws JiBXException 
891
     * @throws NotImplemented 
892
     * @throws InvalidSystemMetadata 
893
     * @throws InsufficientResources 
894
     * @throws UnsupportedType 
895
     * @throws IdentifierNotUnique 
896
     * @throws NotAuthorized 
897
     * @throws InvalidToken 
898
     * @throws NotFound 
975 899
     */
976
    protected void putObject(String pid, String action) {
900
    protected void putObject(String pid, String action) throws ServiceFailure, InvalidRequest, FileNotFoundException, JiBXException, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, NotFound {
977 901
        System.out.println("putObject with pid " + pid);
978 902
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
979 903
        OutputStream out = null;
......
984 908
        } catch (IOException e1) {
985 909
            logMetacat.error("Could not get the output stream for writing in putObject");
986 910
        }
987
        try {
988
            
989
            // Read the incoming data from its Mime Multipart encoding
990
            logMetacat.debug("Disassembling MIME multipart form");
991
            InputStream object = null;
992
            InputStream sysmeta = null;
993
            Map<String, List<String>> multipartparams;
994
            
995
            try {
911
        
912
        // Read the incoming data from its Mime Multipart encoding
913
    	Map<String, File> files = collectMultipartFiles();
914
        InputStream object = null;
915
        InputStream sysmeta = null;
996 916

  
997
                // handle MMP inputs
998
                File tmpDir = getTempDirectory();
999
                System.out.println("temp dir: " + tmpDir.getAbsolutePath());
1000
                MultipartRequestResolver mrr = 
1001
                	new MultipartRequestResolver(tmpDir.getAbsolutePath(), 1000000000, 0);
1002
                MultipartRequest mr = mrr.resolveMultipart(request);
1003
                System.out.println("resolved multipart request");
1004
                Map<String, File> files = mr.getMultipartFiles();
1005
                if (files == null) {
1006
                    throw new ServiceFailure("1202", "create/update must have multipart files with names 'object' and 'sysmeta'");
1007
                }
1008
                System.out.println("got multipart files");
1009
                
1010
                if (files.keySet() == null) {
1011
                    System.out.println("No file keys in MMP request.");
1012
                    throw new ServiceFailure("1202", "No file keys found in MMP.  " +
1013
                            "create/update must have multipart files with names 'object' and 'sysmeta'");
1014
                }
917
        File smFile = files.get("sysmeta");
918
        sysmeta = new FileInputStream(smFile);
919
        File objFile = files.get("object");
920
        object = new FileInputStream(objFile);
921
        
922
        if (action.equals(FUNCTION_NAME_INSERT)) { 
923
            // handle inserts
924
            logMetacat.debug("Commence creation...");
925
            SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
1015 926

  
1016
				// for logging purposes, dump out the key-value pairs that constitute the request
1017
				// 3 types exist: request params, multipart params, and multipart files
1018
                Iterator it = files.keySet().iterator();
1019
                System.out.println("iterating through files");
1020
                while (it.hasNext()) {
1021
                    String key = (String)it.next();
1022
                    System.out.println("files key: " + key);
1023
                    System.out.println("files value: " + files.get(key));
1024
                }
1025
                
1026
                multipartparams = mr.getMultipartParameters();
1027
                it = multipartparams.keySet().iterator();
1028
                System.out.println("iterating through multipartparams");
1029
                while (it.hasNext()) {
1030
                    String key = (String)it.next();
1031
                    System.out.println("multipartparams key: " + key);
1032
                    System.out.println("multipartparams value: " + multipartparams.get(key));
1033
                }
1034
                
1035
                it = params.keySet().iterator();
1036
                System.out.println("iterating through params");
1037
                while (it.hasNext()) {
1038
                    String key = (String)it.next();
1039
                    System.out.println("param key: " + key);
1040
                    System.out.println("param value: " + params.get(key));
1041
                }
1042
                System.out.println("done iterating the request...");
1043

  
1044
                File smFile = files.get("sysmeta");
1045
				if (smFile == null) {
1046
				    throw new InvalidRequest("1102", "Missing the required file-part 'sysmeta' from the multipart request.");
1047
				}
1048
                System.out.println("smFile: " + smFile.getAbsolutePath());
1049
                sysmeta = new FileInputStream(smFile);
1050
                File objFile = files.get("object");
1051
				if (objFile == null) {
1052
				    throw new InvalidRequest("1102", "Missing the required file-part 'object' from the multipart request.");
1053
				}
1054
                System.out.println("objectfile: " + objFile.getAbsolutePath());
1055
                object = new FileInputStream(objFile);
1056
                
1057
            }
1058
            catch (FileUploadException fue)
1059
            {
1060
                throw new ServiceFailure("1202", "Could not upload MMP files: " + fue.getMessage());
1061
            }
1062
            catch (IOException ioe)
1063
            {
1064
                throw new ServiceFailure("1202", 
1065
                        "IOException when processing Mime Multipart: " + ioe.getMessage());
1066
            }
1067
            catch (Exception e)
1068
            {
1069
                throw new ServiceFailure("1202", "Error handling MMP upload: " + e.getClass() + ": " + e.getMessage());
1070
            }
927
            Identifier id = new Identifier();
928
            id.setValue(pid);
929
            System.out.println("creating object with pid " + pid);
930
            Identifier rId = MNodeService.getInstance().create(session, id, object, smd);
931
            serializeServiceType(Identifier.class, rId, out);
1071 932
            
1072
            // handle inserts
1073
            if (action.equals(FUNCTION_NAME_INSERT)) { 
1074

  
1075
                logMetacat.debug("Commence creation...");
1076
                SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
1077

  
1078
                Identifier id = new Identifier();
1079
                id.setValue(pid);
1080
                System.out.println("creating object with pid " + pid);
1081
                Identifier rId = MNodeService.getInstance().create(session, id, object, smd);
1082
                serializeServiceType(Identifier.class, rId, out);
1083
                
1084
            } else if (action.equals(FUNCTION_NAME_UPDATE)) { 
1085

  
1086
                // check that the newPid parameter was provided
1087
                if (multipartparams.get("newPid") == null) {
1088
                    throw new InvalidRequest("1202", "'newPid' must be contained in the request parameters.");
1089
                }
1090
                String newPidString = multipartparams.get("newPid").get(0);
1091
                
1092
                Identifier newPid = new Identifier();
1093
                Identifier obsoletedPid = new Identifier();
933
        } else if (action.equals(FUNCTION_NAME_UPDATE)) {
934
        	// handle updates
935
        	
936
            // construct pids
937
            Identifier newPid = new Identifier();
938
            try {
939
            	String newPidString = multipartparams.get("newPid").get(0);
1094 940
                newPid.setValue(newPidString);
1095
                obsoletedPid.setValue(pid);
1096
               
1097
                logMetacat.debug("Commence update...");
1098
                
1099
                //get the systemmetadata object
1100
                SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
941
            } catch (Exception e) {
942
				logMetacat.warn("newPid not given");
943
			}
944
            
945
            Identifier obsoletedPid = new Identifier();
946
            obsoletedPid.setValue(pid);
947
           
948
            logMetacat.debug("Commence update...");
949
            
950
            // get the systemmetadata object
951
            SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
1101 952

  
1102
                Identifier rId = MNodeService.getInstance().update(session, newPid, object, obsoletedPid, smd);
1103
                serializeServiceType(Identifier.class, rId, out);
1104
            } else {
1105
                throw new InvalidRequest("1000", "Operation must be create or update.");
1106
            }
953
            Identifier rId = MNodeService.getInstance().update(session, newPid, object, obsoletedPid, smd);
954
            serializeServiceType(Identifier.class, rId, out);
955
        } else {
956
            throw new InvalidRequest("1000", "Operation must be create or update.");
957
        }
1107 958
            
1108
            //clean up the MMP files
1109
            //parts.get("systemmetadata").delete();
1110
            //parts.get("object").delete();
1111
        } catch (NotAuthorized e) {
1112
            response.setStatus(500);
1113
            serializeException(e, out);
1114
        } catch (InvalidToken e) {
1115
            response.setStatus(500);
1116
            serializeException(e, out);
1117
        } catch (ServiceFailure e) {
1118
            response.setStatus(500);
1119
            serializeException(e, out);
1120
        } catch (NotFound e) {
1121
            response.setStatus(500);
1122
            serializeException(e, out);
1123
        } catch (IdentifierNotUnique e) {
1124
            response.setStatus(500);
1125
            serializeException(e, out);
1126
        } catch (UnsupportedType e) {
1127
            response.setStatus(500);
1128
            serializeException(e, out);
1129
        } catch (InsufficientResources e) {
1130
            response.setStatus(500);
1131
            serializeException(e, out);
1132
        } catch (InvalidSystemMetadata e) {
1133
            response.setStatus(500);
1134
            serializeException(e, out);
1135
        } catch (NotImplemented e) {
1136
            response.setStatus(500);
1137
            serializeException(e, out);
1138
        } catch (InvalidRequest e) {
1139
            response.setStatus(500);
1140
            serializeException(e, out);
1141
        } catch (JiBXException e) {
1142
            response.setStatus(500);
1143
            e.printStackTrace(System.out);
1144
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
1145
            serializeException(ism, out);
1146
        }
959
            
1147 960
    }
1148 961

  
1149 962
    /**
src/edu/ucsb/nceas/metacat/restservice/CNResourceHandler.java
31 31
import java.io.PrintWriter;
32 32
import java.util.Date;
33 33
import java.util.Hashtable;
34
import java.util.Iterator;
35
import java.util.List;
36 34
import java.util.Map;
37 35
import java.util.Timer;
38 36

  
......
40 38
import javax.servlet.http.HttpServletRequest;
41 39
import javax.servlet.http.HttpServletResponse;
42 40

  
41
import org.apache.commons.fileupload.FileUploadException;
43 42
import org.apache.commons.io.IOUtils;
44 43
import org.apache.log4j.Logger;
45 44
import org.dataone.client.ObjectFormatCache;
46 45
import org.dataone.client.auth.CertificateManager;
47
import org.dataone.mimemultipart.MultipartRequest;
48
import org.dataone.mimemultipart.MultipartRequestResolver;
49 46
import org.dataone.service.exceptions.BaseException;
50 47
import org.dataone.service.exceptions.IdentifierNotUnique;
51 48
import org.dataone.service.exceptions.InsufficientResources;
......
69 66
import org.dataone.service.types.Permission;
70 67
import org.dataone.service.types.Subject;
71 68
import org.dataone.service.types.SystemMetadata;
72
import org.jibx.runtime.BindingDirectory;
73
import org.jibx.runtime.IBindingFactory;
74
import org.jibx.runtime.IUnmarshallingContext;
75 69
import org.jibx.runtime.JiBXException;
76 70

  
77
import edu.ucsb.nceas.metacat.IdentifierManager;
78 71
import edu.ucsb.nceas.metacat.MetacatHandler;
79 72
import edu.ucsb.nceas.metacat.dataone.CNodeService;
80 73

  
......
585 578
     * 
586 579
     * @param guid - ID of data object to be inserted or updated.  If action is update, the pid
587 580
     *               is the existing pid.  If insert, the pid is the new one
588
     * @throws IOException
581
     * @throws InvalidRequest 
582
     * @throws ServiceFailure 
583
     * @throws IdentifierNotUnique 
584
     * @throws JiBXException 
585
     * @throws NotImplemented 
586
     * @throws InvalidSystemMetadata 
587
     * @throws InsufficientResources 
588
     * @throws UnsupportedType 
589
     * @throws NotAuthorized 
590
     * @throws InvalidToken 
591
     * @throws IOException 
589 592
     */
590
    protected void putObject(String pid, String action) {
591
        logMetacat.debug("putObject with pid " + pid);
593
    protected void putObject(String pid, String action) throws ServiceFailure, InvalidRequest, IdentifierNotUnique, JiBXException, InvalidToken, NotAuthorized, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, IOException {
592 594
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
593
        OutputStream out = null;
594
        try {
595
            out = response.getOutputStream();
596
            response.setStatus(200);
597
            response.setContentType("text/xml");
598
        } catch (IOException e1) {
599
            logMetacat.error("Could not get the output stream for writing in putObject");
600
        }
601
        try {
602
            
603
            // Read the incoming data from its Mime Multipart encoding
604
            logMetacat.debug("Disassembling MIME multipart form");
605
            InputStream object = null;
606
            InputStream sysmeta = null;
607
            Map<String, List<String>> multipartparams;
608
            
609
            try
610
            {
611
                //String req = IOUtils.toString(request.getInputStream());
612
                //logMetacat.debug("request: " + req);
613
                //InputStream reqStr = IOUtils.toInputStream(req);
614
                InputStream reqStr = request.getInputStream();
615
                
616
                //handle MMP inputs
617
                File tmpDir = getTempDirectory();
618
                File tmpSMFile = new File(tmpDir + 
619
                        ".sysmeta." + new Date().getTime() + ".tmp");
620
                logMetacat.debug("temp dir: " + tmpDir.getAbsolutePath());
621
                MultipartRequestResolver mrr = new MultipartRequestResolver(
622
                        tmpDir.getAbsolutePath(), 1000000000, 0);
623
                MultipartRequest mr = mrr.resolveMultipart(request);
624
                logMetacat.debug("resolved multipart request");
625
                Map<String, File> files = mr.getMultipartFiles();
626
                if(files == null)
627
                {
628
                    throw new ServiceFailure("1202", "create/update must have multipart files with names 'object' and 'sysmeta'");
629
                }
630
                logMetacat.debug("got multipart files");
631
                
632
                if(files.keySet() == null)
633
                {
634
                    logMetacat.error("No file keys in MMP request.");
635
                    throw new ServiceFailure("1202", "No file keys found in MMP.  " +
636
                            "create/update must have multipart files with names 'object' and 'sysmeta'");
637
                }
595
        
596
        // Read the incoming data from its Mime Multipart encoding
597
    	Map<String, File> files = collectMultipartFiles();
598
        InputStream object = null;
599
        InputStream sysmeta = null;
638 600

  
639
		// for logging purposes, dump out the key-value pairs that constitute the request
640
		// 3 types exist: request params, multipart params, and multipart files
641
                Iterator it = files.keySet().iterator();
642
                logMetacat.debug("iterating through request parts: " + it);
643
                while(it.hasNext())
644
                {
645
                    String key = (String)it.next();
646
                    logMetacat.debug("files key: " + key);
647
                    logMetacat.debug("files value: " + files.get(key));
648
                }
649
                
650
                multipartparams = mr.getMultipartParameters();
651
                it = multipartparams.keySet().iterator();
652
                while(it.hasNext())
653
                {
654
                    String key = (String)it.next();
655
                    logMetacat.debug("multipartparams key: " + key);
656
                    logMetacat.debug("multipartparams value: " + multipartparams.get(key));
657
                }
658
                
659
                it = params.keySet().iterator();
660
                while(it.hasNext())
661
                {
662
                    String key = (String)it.next();
663
                    logMetacat.debug("param key: " + key);
664
                    logMetacat.debug("param value: " + params.get(key));
665
                }
666
		logMetacat.debug("done iterating the request...");
601
        File smFile = files.get("sysmeta");
602
        sysmeta = new FileInputStream(smFile);
603
        File objFile = files.get("object");
604
        object = new FileInputStream(objFile);
605
       
606
        if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
667 607

  
668
                File smFile = files.get("sysmeta");
669
		if (smFile == null) 
670
		    throw new InvalidRequest("1102", "Missing the required file-part 'sysmeta' from the multipart request.");
671
                logMetacat.debug("smFile: " + smFile.getAbsolutePath());
672
                sysmeta = new FileInputStream(smFile);
673
                File objFile = files.get("object");
674
		if (objFile == null) 
675
		    throw new InvalidRequest("1102", "Missing the required file-part 'object' from the multipart request.");
608
            logMetacat.debug("Commence creation...");
609
            SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
676 610

  
677
                logMetacat.debug("objectfile: " + objFile.getAbsolutePath());
678
                object = new FileInputStream(objFile);
679
                
680
                /*String obj = IOUtils.toString(object);
681
                String sm = IOUtils.toString(sysmeta);
682
                logMetacat.debug("object: " + obj);
683
                logMetacat.debug("sm: " + sm);
684
                object = IOUtils.toInputStream(obj);
685
                sysmeta = IOUtils.toInputStream(sm);*/
686
                
687
            }
688
            catch(org.apache.commons.fileupload.FileUploadException fue)
689
            {
690
                throw new ServiceFailure("1202", "Could not upload MMP files: " + fue.getMessage());
691
            }
692
            catch(IOException ioe)
693
            {
694
                throw new ServiceFailure("1202", 
695
                        "IOException when processing Mime Multipart: " + ioe.getMessage());
696
            }
697
            catch(Exception e)
698
            {
699
                throw new ServiceFailure("1202", "Error handling MMP upload: " + e.getClass() + ": " + e.getMessage());
700
            }
611
            Identifier id = new Identifier();
612
            id.setValue(pid);
613
            logMetacat.debug("creating object with pid " + id.getValue());
614
            Identifier rId = CNodeService.getInstance().create(session, id, object, smd);
701 615
            
702
            if ( action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
703

  
704
                // Check if the objectId exists
705
                IdentifierManager im = IdentifierManager.getInstance();
706
                if (im.identifierExists(pid)) {
707
                    throw new IdentifierNotUnique("1000", "Identifier is already in use: " + pid);
708
                }
709

  
710
                logMetacat.debug("Commence creation...");
711
                IBindingFactory bfact =
712
                    BindingDirectory.getFactory(SystemMetadata.class);
713
                IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
714
                SystemMetadata smd = (SystemMetadata) uctx.unmarshalDocument(sysmeta, null);
715

  
716
                Identifier id = new Identifier();
717
                id.setValue(pid);
718
                logMetacat.debug("creating object with pid " + id.getValue());
719
                Identifier rId = CNodeService.getInstance().create(session, id, object, smd);
720
                serializeServiceType(Identifier.class, rId, out);
721
                
722
            } else {
723
                throw new InvalidRequest("1000", "Operation must be create or update.");
724
            }
616
            OutputStream out = response.getOutputStream();
617
            response.setStatus(200);
618
            response.setContentType("text/xml");
725 619
            
726
            //clean up the MMP files
727
            //parts.get("systemmetadata").delete();
728
            //parts.get("object").delete();
729
        } catch (NotAuthorized e) {
730
            response.setStatus(500);
731
            serializeException(e, out);
732
        } catch (InvalidToken e) {
733
            response.setStatus(500);
734
            serializeException(e, out);
735
        } catch (ServiceFailure e) {
736
            response.setStatus(500);
737
            serializeException(e, out);
738
        } catch (IdentifierNotUnique e) {
739
            response.setStatus(500);
740
            serializeException(e, out);
741
        } catch (UnsupportedType e) {
742
            response.setStatus(500);
743
            serializeException(e, out);
744
        } catch (InsufficientResources e) {
745
            response.setStatus(500);
746
            serializeException(e, out);
747
        } catch (InvalidSystemMetadata e) {
748
            response.setStatus(500);
749
            serializeException(e, out);
750
        } catch (NotImplemented e) {
751
            response.setStatus(500);
752
            serializeException(e, out);
753
        } catch (InvalidRequest e) {
754
            response.setStatus(500);
755
            serializeException(e, out);
756
        } /*catch (MessagingException e) {
757
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
758
            serializeException(sf, out);
759
        } catch (IOException e) {
760
            response.setStatus(500);
761
            ServiceFailure sf = new ServiceFailure("1000", e.getMessage());
762
            serializeException(sf, out);
763
        }*/ catch (JiBXException e) {
764
            response.setStatus(500);
765
            e.printStackTrace(System.out);
766
            InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e.getMessage());
767
            serializeException(ism, out);
620
            serializeServiceType(Identifier.class, rId, out);
621
            
622
        } else {
623
            throw new InvalidRequest("1000", "Operation must be create.");
768 624
        }
769 625
    }
770 626

  
......
974 830
    /**
975 831
     * Register System Metadata without data or metadata object
976 832
     * @param pid identifier for System Metadata entry
833
     * @throws JiBXException 
834
     * @throws FileUploadException 
835
     * @throws IOException 
836
     * @throws InvalidRequest 
837
     * @throws ServiceFailure 
838
     * @throws InvalidSystemMetadata 
839
     * @throws NotAuthorized 
840
     * @throws NotImplemented 
977 841
     */
978
    protected void registerSystemMetadata(String pid) {
842
    protected boolean registerSystemMetadata(String pid) throws ServiceFailure, InvalidRequest, IOException, FileUploadException, JiBXException, NotImplemented, NotAuthorized, InvalidSystemMetadata {
979 843
		logMetacat.debug("Entering registerSystemMetadata: " + pid);
980
		OutputStream out = null;
981
		try {
982
			out = response.getOutputStream();
983
			response.setStatus(200);
984
			response.setContentType("text/xml");
985
		} catch (IOException e1) {
986
			logMetacat.error("Could not get the output stream for writing in putObject");
987
		}
988
		try {
989 844

  
990
			// Read the incoming data from its Mime Multipart encoding
991
			logMetacat.debug("Disassembling MIME multipart form");
992
			InputStream sysmeta = null;
993
			Map<String, List<String>> multipartparams;
845
		// get the system metadata from the request
846
		SystemMetadata systemMetadata = collectSystemMetadata();
994 847

  
995
			try {
996

  
997
				// handle MMP inputs
998
				File tmpDir = getTempDirectory();
999

  
1000
				logMetacat.debug("temp dir: " + tmpDir.getAbsolutePath());
1001
				MultipartRequestResolver mrr = new MultipartRequestResolver(
1002
						tmpDir.getAbsolutePath(), 1000000000, 0);
1003
				MultipartRequest mr = mrr.resolveMultipart(request);
1004
				logMetacat.debug("resolved multipart request");
1005
				Map<String, File> files = mr.getMultipartFiles();
1006
				if (files == null) {
1007
					throw new ServiceFailure("1202",
1008
							"register meta must have multipart file with name 'sysmeta'");
1009
				}
1010
				logMetacat.debug("got multipart files");
1011

  
1012
				if (files.keySet() == null) {
1013
					logMetacat.error("No file keys in MMP request.");
1014
					throw new ServiceFailure(
1015
							"1202",
1016
							"No file keys found in MMP.  "
1017
									+ "register meta must have multipart file with name 'sysmeta'");
1018
				}
1019

  
1020
				// for logging purposes, dump out the key-value pairs that
1021
				// constitute the request
1022
				// 3 types exist: request params, multipart params, and
1023
				// multipart files
1024
				Iterator it = files.keySet().iterator();
1025
				logMetacat.debug("iterating through request parts: " + it);
1026
				while (it.hasNext()) {
1027
					String key = (String) it.next();
1028
					logMetacat.debug("files key: " + key);
1029
					logMetacat.debug("files value: " + files.get(key));
1030
				}
1031

  
1032
				multipartparams = mr.getMultipartParameters();
1033
				it = multipartparams.keySet().iterator();
1034
				while (it.hasNext()) {
1035
					String key = (String) it.next();
1036
					logMetacat.debug("multipartparams key: " + key);
1037
					logMetacat.debug("multipartparams value: "
1038
							+ multipartparams.get(key));
1039
				}
1040

  
1041
				it = params.keySet().iterator();
1042
				while (it.hasNext()) {
1043
					String key = (String) it.next();
1044
					logMetacat.debug("param key: " + key);
1045
					logMetacat.debug("param value: " + params.get(key));
1046
				}
1047
				logMetacat.debug("done iterating the request...");
1048

  
1049
				File smFile = files.get("sysmeta");
1050
				if (smFile == null) {
1051
					throw new InvalidRequest("1102",
1052
							"Missing the required file-part 'sysmeta' from the multipart request.");
1053
				}
1054
				logMetacat.debug("smFile: " + smFile.getAbsolutePath());
1055
				sysmeta = new FileInputStream(smFile);
1056

  
1057
			} catch (org.apache.commons.fileupload.FileUploadException fue) {
1058
				throw new ServiceFailure("1202", "Could not upload MMP files: "
1059
						+ fue.getMessage());
1060
			} catch (IOException ioe) {
1061
				throw new ServiceFailure("1202",
1062
						"IOException when processing Mime Multipart: "
1063
								+ ioe.getMessage());
1064
			} catch (Exception e) {
1065
				throw new ServiceFailure("1202", "Error handling MMP upload: "
1066
						+ e.getClass() + ": " + e.getMessage());
1067
			}
1068

  
1069
			// Check if the objectId exists
1070
			IdentifierManager im = IdentifierManager.getInstance();
1071
			if (im.identifierExists(pid)) {
1072
				throw new IdentifierNotUnique("1000",
1073
						"Identifier is already in use: " + pid);
1074
			}
1075

  
1076
			logMetacat.debug("Commence creation...");
1077
			IBindingFactory bfact = BindingDirectory
1078
					.getFactory(SystemMetadata.class);
1079
			IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1080
			SystemMetadata systemMetadata = (SystemMetadata) uctx
1081
					.unmarshalDocument(sysmeta, null);
1082

  
1083
			Identifier guid = new Identifier();
1084
			guid.setValue(pid);
1085
			logMetacat.debug("registering system metadata with pid "
1086
					+ guid.getValue());
1087
			boolean result = CNodeService.getInstance().registerSystemMetadata(
1088
					session, guid, systemMetadata);
1089
			serializeServiceType(Boolean.class, result, out);
1090

  
1091
		} catch (NotAuthorized e) {
1092
			response.setStatus(500);
1093
			serializeException(e, out);
1094
		} catch (ServiceFailure e) {
1095
			response.setStatus(500);
1096
			serializeException(e, out);
1097
		} catch (IdentifierNotUnique e) {
1098
			response.setStatus(500);
1099
			serializeException(e, out);
1100
		} catch (NotImplemented e) {
1101
			response.setStatus(500);
1102
			serializeException(e, out);
1103
		} catch (InvalidRequest e) {
1104
			response.setStatus(500);
1105
			serializeException(e, out);
1106
		} catch (JiBXException e) {
1107
			response.setStatus(500);
1108
			e.printStackTrace(System.out);
1109
			InvalidSystemMetadata ism = new InvalidSystemMetadata("1080", e
1110
					.getMessage());
1111
			serializeException(ism, out);
1112
		} catch (InvalidSystemMetadata e) {
1113
			serializeException(e, out);
1114
    }
848
		Identifier guid = new Identifier();
849
		guid.setValue(pid);
850
		logMetacat.debug("registering system metadata with pid " + guid.getValue());
851
		boolean result = CNodeService.getInstance().registerSystemMetadata(session, guid, systemMetadata);
852
		
853
		response.setStatus(200);
854
		response.setContentType("text/xml");
855
		return result;
856
			
1115 857
	}
1116 858
    
1117 859
    /**
src/edu/ucsb/nceas/metacat/restservice/D1ResourceHandler.java
23 23
package edu.ucsb.nceas.metacat.restservice;
24 24

  
25 25
import java.io.File;
26
import java.io.FileInputStream;
27
import java.io.FileNotFoundException;
26 28
import java.io.IOException;
27 29
import java.io.InputStream;
28 30
import java.io.OutputStream;
......
33 35
import java.util.Date;
34 36
import java.util.Enumeration;
35 37
import java.util.Hashtable;
38
import java.util.Iterator;
39
import java.util.List;
40
import java.util.Map;
36 41
import java.util.TimeZone;
37 42
import java.util.Timer;
38 43

  
......
40 45
import javax.servlet.http.HttpServletRequest;
41 46
import javax.servlet.http.HttpServletResponse;
42 47

  
48
import org.apache.commons.fileupload.FileUploadException;
43 49
import org.apache.commons.io.IOUtils;
44 50
import org.apache.log4j.Logger;
45 51
import org.dataone.client.auth.CertificateManager;
52
import org.dataone.mimemultipart.MultipartRequest;
53
import org.dataone.mimemultipart.MultipartRequestResolver;
46 54
import org.dataone.service.exceptions.BaseException;
55
import org.dataone.service.exceptions.InvalidRequest;
56
import org.dataone.service.exceptions.ServiceFailure;
47 57
import org.dataone.service.types.Session;
58
import org.dataone.service.types.SystemMetadata;
48 59
import org.dataone.service.types.util.ServiceTypeUtil;
49 60
import org.jibx.runtime.JiBXException;
50 61

  
......
115 126
    protected String[] groupNames;
116 127

  
117 128
    protected Hashtable<String, String[]> params;
129
    protected Map<String, List<String>> multipartparams;
118 130
    
119 131
    // D1 certificate-based authentication
120 132
    protected Session session;
......
155 167
        }
156 168
    }
157 169
    
170
    protected SystemMetadata collectSystemMetadata() throws IOException, FileUploadException, ServiceFailure, InvalidRequest, JiBXException  {
171
		
172
		// Read the incoming data from its Mime Multipart encoding
173
		logMetacat.debug("Disassembling MIME multipart form");
174
		InputStream sysmeta = null;
175

  
176
		// handle MMP inputs
177
		File tmpDir = getTempDirectory();
178
		logMetacat.debug("temp dir: " + tmpDir.getAbsolutePath());
179
		MultipartRequestResolver mrr = 
180
			new MultipartRequestResolver(tmpDir.getAbsolutePath(), 1000000000, 0);
181
		MultipartRequest mr = null;
182
		try {
183
			mr = mrr.resolveMultipart(request);
184
		} catch (Exception e) {
185
			throw new ServiceFailure("1202", 
186
					"Could not resolve multipart: " + e.getMessage());
187
		}
188
		logMetacat.debug("resolved multipart request");
189
		Map<String, File> files = mr.getMultipartFiles();
190
		if (files == null) {
191
			throw new ServiceFailure("1202",
192
					"register meta must have multipart file with name 'sysmeta'");
193
		}
194
		logMetacat.debug("got multipart files");
195

  
196
		if (files.keySet() == null) {
197
			logMetacat.error("No file keys in MMP request.");
198
			throw new ServiceFailure(
199
					"1202",
200
					"No file keys found in MMP.  "
201
							+ "register meta must have multipart file with name 'sysmeta'");
202
		}
203

  
204
		// for logging purposes, dump out the key-value pairs that
205
		// constitute the request
206
		// 3 types exist: request params, multipart params, and
207
		// multipart files
208
		Iterator it = files.keySet().iterator();
209
		logMetacat.debug("iterating through request parts: " + it);
210
		while (it.hasNext()) {
211
			String key = (String) it.next();
212
			logMetacat.debug("files key: " + key);
213
			logMetacat.debug("files value: " + files.get(key));
214
		}
215

  
216
		multipartparams = mr.getMultipartParameters();
217
		it = multipartparams.keySet().iterator();
218
		while (it.hasNext()) {
219
			String key = (String) it.next();
220
			logMetacat.debug("multipartparams key: " + key);
221
			logMetacat.debug("multipartparams value: " + multipartparams.get(key));
222
		}
223

  
224
		it = params.keySet().iterator();
225
		while (it.hasNext()) {
226
			String key = (String) it.next();
227
			logMetacat.debug("param key: " + key);
228
			logMetacat.debug("param value: " + params.get(key));
229
		}
230
		logMetacat.debug("done iterating the request...");
231

  
232
		File smFile = files.get("sysmeta");
233
		if (smFile == null) {
234
			throw new InvalidRequest("1102",
235
					"Missing the required file-part 'sysmeta' from the multipart request.");
236
		}
237
		logMetacat.debug("smFile: " + smFile.getAbsolutePath());
238
		sysmeta = new FileInputStream(smFile);
239
	
240
		logMetacat.debug("Commence creation...");
241
		SystemMetadata systemMetadata = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
242
		return systemMetadata;
243
	}
244
    
245
    protected Map<String, File> collectMultipartFiles() throws ServiceFailure, InvalidRequest {
246
    	
247
        // Read the incoming data from its Mime Multipart encoding
248
        logMetacat.debug("Disassembling MIME multipart form");
249
        InputStream object = null;
250
        InputStream sysmeta = null;
251
        
252
        
253
        // handle MMP inputs
254
        File tmpDir = getTempDirectory();
255
        System.out.println("temp dir: " + tmpDir.getAbsolutePath());
256
        MultipartRequestResolver mrr = 
257
        	new MultipartRequestResolver(tmpDir.getAbsolutePath(), 1000000000, 0);
258
        MultipartRequest mr = null;
259
		try {
260
			mr = mrr.resolveMultipart(request);
261
		} catch (Exception e) {
262
            throw new ServiceFailure("1202", 
263
            		"Could not resolve multipart files: " + e.getMessage());
264
		}
265
        System.out.println("resolved multipart request");
266
        Map<String, File> files = mr.getMultipartFiles();
267
        if (files == null) {
268
            throw new ServiceFailure("1202", "create/update must have multipart files with names 'object' and 'sysmeta'");
269
        }
270
        System.out.println("got multipart files");
271
        
272
        if (files.keySet() == null) {
273
            System.out.println("No file keys in MMP request.");
274
            throw new ServiceFailure("1202", "No file keys found in MMP.  " +
275
                    "create/update must have multipart files with names 'object' and 'sysmeta'");
276
        }
277

  
278
		// for logging purposes, dump out the key-value pairs that constitute the request
279
		// 3 types exist: request params, multipart params, and multipart files
280
        Iterator it = files.keySet().iterator();
281
        System.out.println("iterating through files");
282
        while (it.hasNext()) {
283
            String key = (String)it.next();
284
            System.out.println("files key: " + key);
285
            System.out.println("files value: " + files.get(key));
286
        }
287
        
288
        multipartparams = mr.getMultipartParameters();
289
        it = multipartparams.keySet().iterator();
290
        System.out.println("iterating through multipartparams");
291
        while (it.hasNext()) {
292
            String key = (String)it.next();
293
            System.out.println("multipartparams key: " + key);
294
            System.out.println("multipartparams value: " + multipartparams.get(key));
295
        }
296
        
297
        it = params.keySet().iterator();
298
        System.out.println("iterating through params");
299
        while (it.hasNext()) {
300
            String key = (String)it.next();
301
            System.out.println("param key: " + key);
302
            System.out.println("param value: " + params.get(key));
303
        }
304
        System.out.println("done iterating the request...");
305

  
306
        File smFile = files.get("sysmeta");
307
		if (smFile == null) {
308
		    throw new InvalidRequest("1102", "Missing the required file-part 'sysmeta' from the multipart request.");
309
		}
310
        System.out.println("smFile: " + smFile.getAbsolutePath());
311
        File objFile = files.get("object");
312
		if (objFile == null) {
313
		    throw new InvalidRequest("1102", "Missing the required file-part 'object' from the multipart request.");
314
		}
315
        System.out.println("objectfile: " + objFile.getAbsolutePath());
316
        
317
        return files;
318
    }
319
    
158 320
		/**
159 321
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
160 322
     */

Also available in: Unified diff