Example usage for javax.xml.soap AttachmentPart setContentId

List of usage examples for javax.xml.soap AttachmentPart setContentId

Introduction

In this page you can find the example usage for javax.xml.soap AttachmentPart setContentId.

Prototype

public void setContentId(String contentId) 

Source Link

Document

Sets the MIME header whose name is "Content-ID" with the given value.

Usage

From source file:eu.domibus.ebms3.sender.EbMS3MessageBuilder.java

private void attachPayload(PartInfo partInfo, SOAPMessage message)
        throws ParserConfigurationException, SOAPException, IOException, SAXException {
    String mimeType = null;/*from w w  w  .  j  a v  a 2  s  . c  o m*/
    boolean compressed = false;
    for (Property prop : partInfo.getPartProperties().getProperties()) {
        if (Property.MIME_TYPE.equals(prop.getName())) {
            mimeType = prop.getValue();
        }
        if (CompressionService.COMPRESSION_PROPERTY_KEY.equals(prop.getName())
                && CompressionService.COMPRESSION_PROPERTY_VALUE.equals(prop.getValue())) {
            compressed = true;
        }
    }
    byte[] binaryData = this.attachmentDAO.loadBinaryData(partInfo.getEntityId());
    DataSource dataSource = new ByteArrayDataSource(binaryData,
            compressed ? CompressionService.COMPRESSION_PROPERTY_VALUE : mimeType);
    DataHandler dataHandler = new DataHandler(dataSource);
    if (partInfo.isInBody() && mimeType != null && mimeType.toLowerCase().contains("xml")) { //TODO: respect empty soap body config
        this.documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = this.documentBuilderFactory.newDocumentBuilder();
        message.getSOAPBody().addDocument(builder.parse(dataSource.getInputStream()));
        partInfo.setHref(null);
        return;
    }
    AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler);
    attachmentPart.setContentId(partInfo.getHref());
    message.addAttachmentPart(attachmentPart);
}

From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java

@SuppressWarnings("unchecked")
protected void getResponse(Document query, SOAPMessage responseMessage, SOAPMessage requestMessage)
        throws Exception {
    XTeeHeader header = metaService ? null : parseXteeHeader(requestMessage);

    // Build request message
    List<XTeeAttachment> attachments = new ArrayList<XTeeAttachment>();
    for (Iterator<AttachmentPart> i = requestMessage.getAttachments(); i.hasNext();) {
        AttachmentPart a = i.next();
        attachments.add(new XTeeAttachment(a.getContentId(), a.getContentType(), a.getRawContentBytes()));
    }/*from   www. j  a  va  2 s  .c  o m*/
    XTeeMessage<Document> request = new BeanXTeeMessage<Document>(header, query, attachments);

    SOAPElement teenusElement = createXteeMessageStructure(requestMessage, responseMessage);
    if (XRoadProtocolVersion.V2_0 == version) {
        if (!metaService) {
            copyParing(query, teenusElement);
        }
        teenusElement = teenusElement.addChildElement("keha");
    }

    // Build response message
    XTeeMessage<Element> response = new BeanXTeeMessage<Element>(header, teenusElement,
            new ArrayList<XTeeAttachment>());

    // Run logic
    invokeInternalEx(request, response, requestMessage, responseMessage);

    // Add any attachments
    for (XTeeAttachment a : response.getAttachments()) {
        AttachmentPart attachment = responseMessage.createAttachmentPart(a.getDataHandler());
        attachment.setContentId("<" + a.getCid() + ">");
        responseMessage.addAttachmentPart(attachment);
    }
}

From source file:it.cnr.icar.eric.server.cms.AbstractContentManagementService.java

protected AttachmentPart getRepositoryItemAsAttachmentPart(String id) throws RegistryException {
    RepositoryItem ri = rm.getRepositoryItem(id);

    AttachmentPart ap = null;

    try {//from   w w  w .j  ava 2 s .  c  om
        SOAPMessage m = mf.createMessage();
        DataHandler dh = ri.getDataHandler();
        String cid = WSS4JSecurityUtilBST.convertUUIDToContentId(id);
        ap = m.createAttachmentPart(dh);
        ap.setContentId(cid);

    } catch (Exception e) {
        throw new RegistryException(e);
    }

    return ap;
}

From source file:com.mirth.connect.connectors.ws.WebServiceMessageDispatcher.java

private void processMessage(MessageObject mo) throws Exception {
    /*//from   w  w  w  .j av  a  2 s.  co  m
     * Initialize the dispatch object if it hasn't been initialized yet, or
     * create a new one if the connector properties have changed due to
     * variables.
     */
    createDispatch(mo);

    SOAPBinding soapBinding = (SOAPBinding) dispatch.getBinding();

    if (connector.isDispatcherUseAuthentication()) {
        dispatch.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, currentUsername);
        dispatch.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, currentPassword);
        logger.debug("Using authentication: username=" + currentUsername + ", password length="
                + currentPassword.length());
    }

    // See: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
    String soapAction = replacer.replaceValues(connector.getDispatcherSoapAction(), mo);

    if (StringUtils.isNotEmpty(soapAction)) {
        dispatch.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
    }

    // build the message
    logger.debug("Creating SOAP envelope.");
    String content = replacer.replaceValues(connector.getDispatcherEnvelope(), mo);
    Source source = new StreamSource(new StringReader(content));
    SOAPMessage message = soapBinding.getMessageFactory().createMessage();
    message.getSOAPPart().setContent(source);

    if (connector.isDispatcherUseMtom()) {
        soapBinding.setMTOMEnabled(true);

        List<String> attachmentIds = connector.getDispatcherAttachmentNames();
        List<String> attachmentContents = connector.getDispatcherAttachmentContents();
        List<String> attachmentTypes = connector.getDispatcherAttachmentTypes();

        for (int i = 0; i < attachmentIds.size(); i++) {
            String attachmentContentId = replacer.replaceValues(attachmentIds.get(i), mo);
            String attachmentContentType = replacer.replaceValues(attachmentTypes.get(i), mo);
            String attachmentContent = replacer.replaceValues(attachmentContents.get(i), mo);

            AttachmentPart attachment = message.createAttachmentPart();
            attachment.setBase64Content(new ByteArrayInputStream(attachmentContent.getBytes("UTF-8")),
                    attachmentContentType);
            attachment.setContentId(attachmentContentId);
            message.addAttachmentPart(attachment);
        }
    }

    message.saveChanges();

    // make the call
    String response = null;
    if (connector.isDispatcherOneWay()) {
        logger.debug("Invoking one way service...");
        dispatch.invokeOneWay(message);
        response = "Invoked one way operation successfully.";
    } else {
        logger.debug("Invoking web service...");
        SOAPMessage result = dispatch.invoke(message);
        response = sourceToXmlString(result.getSOAPPart().getContent());
    }
    logger.debug("Finished invoking web service, got result.");

    // process the result
    messageObjectController.setSuccess(mo, response, null);

    // send to reply channel
    if (connector.getDispatcherReplyChannelId() != null
            && !connector.getDispatcherReplyChannelId().equals("sink")) {
        new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true);
    }
}

From source file:eu.domibus.ebms3.receiver.MSHWebservice.java

/**
 * This method persists incoming messages into the database (and handles decompression before)
 *
 * @param request          the message to persist
 * @param legConfiguration processing information for the message
 * @throws SOAPException//w  ww.  j  ava  2s. c o m
 * @throws JAXBException
 * @throws TransformerException
 * @throws IOException
 * @throws EbMS3Exception
 */
//TODO: improve error handling
private String persistReceivedMessage(SOAPMessage request, LegConfiguration legConfiguration, String pmodeKey,
        Messaging messaging) throws SOAPException, JAXBException, TransformerException, EbMS3Exception {

    boolean bodyloadFound = false;
    for (PartInfo partInfo : messaging.getUserMessage().getPayloadInfo().getPartInfo()) {
        String cid = partInfo.getHref();
        MSHWebservice.LOG.debug("looking for attachment with cid: " + cid);
        boolean payloadFound = false;
        if (cid == null || cid.isEmpty()) {
            if (bodyloadFound) {
                throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0003,
                        "More than one Partinfo without CID found",
                        messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING);
            }
            bodyloadFound = true;
            payloadFound = true;
            partInfo.setInBody(true);
            Node bodyContent = (((Node) request.getSOAPBody().getChildElements().next()));
            Source source = new DOMSource(bodyContent);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Result result = new StreamResult(out);
            Transformer transformer = this.transformerFactory.newTransformer();
            transformer.transform(source, result);
            partInfo.setBinaryData(out.toByteArray());
        }
        @SuppressWarnings("unchecked")
        Iterator<AttachmentPart> attachmentIterator = request.getAttachments();
        AttachmentPart attachmentPart;
        while (attachmentIterator.hasNext() && !payloadFound) {

            attachmentPart = attachmentIterator.next();
            //remove square brackets from cid for further processing
            attachmentPart.setContentId(AttachmentUtil.cleanContentId(attachmentPart.getContentId()));
            MSHWebservice.LOG.debug("comparing with: " + attachmentPart.getContentId());
            if (attachmentPart.getContentId().equals(AttachmentUtil.cleanContentId(cid))) {
                partInfo.setBinaryData(attachmentPart.getRawContentBytes());
                partInfo.setInBody(false);
                payloadFound = true;
            }
        }
        if (!payloadFound) {
            throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0011,
                    "No Attachment found for cid: " + cid + " of message: "
                            + messaging.getUserMessage().getMessageInfo().getMessageId(),
                    messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING);
        }
    }

    boolean compressed = this.compressionService.handleDecompression(messaging.getUserMessage(),
            legConfiguration);
    this.payloadProfileValidator.validate(messaging, pmodeKey);
    this.propertyProfileValidator.validate(messaging, pmodeKey);

    MSHWebservice.LOG.debug("Compression for message with id: "
            + messaging.getUserMessage().getMessageInfo().getMessageId() + " applied: " + compressed);
    MessageLogEntry messageLogEntry = new MessageLogEntry();
    messageLogEntry.setMessageId(messaging.getUserMessage().getMessageInfo().getMessageId());
    messageLogEntry.setMessageType(MessageType.USER_MESSAGE);
    messageLogEntry.setMshRole(MSHRole.RECEIVING);
    messageLogEntry.setReceived(new Date());
    String mpc = messaging.getUserMessage().getMpc();
    messageLogEntry.setMpc((mpc == null || mpc.isEmpty()) ? Mpc.DEFAULT_MPC : mpc);
    messageLogEntry.setMessageStatus(MessageStatus.RECEIVED);

    this.messageLogDao.create(messageLogEntry);
    this.messagingDao.create(messaging);
    return messageLogEntry.getMessageId();

}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

private void addAttachment(SOAPMessage msg, String id, DataHandler dh)
        throws FileNotFoundException, MessagingException, RegistryException {
    String cid = WSS4JSecurityUtilSAML.convertUUIDToContentId(id);
    AttachmentPart ap = msg.createAttachmentPart(dh);
    ap.setContentId(cid);
    msg.addAttachmentPart(ap);/*from w w w .  j  ava2  s.  c om*/

    if (log.isTraceEnabled()) {
        log.trace("adding attachment: contentId=" + cid);
    }
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    WebServiceDispatcherProperties webServiceDispatcherProperties = (WebServiceDispatcherProperties) connectorProperties;

    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.SENDING));

    String responseData = null;/*  w ww .  j a  va2  s. com*/
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    try {
        long dispatcherId = getDispatcherId();
        DispatchContainer dispatchContainer = dispatchContainers.get(dispatcherId);
        if (dispatchContainer == null) {
            dispatchContainer = new DispatchContainer();
            dispatchContainers.put(dispatcherId, dispatchContainer);
        }

        /*
         * Initialize the dispatch object if it hasn't been initialized yet, or create a new one
         * if the connector properties have changed due to variables.
         */
        createDispatch(webServiceDispatcherProperties, dispatchContainer);

        Dispatch<SOAPMessage> dispatch = dispatchContainer.getDispatch();

        configuration.configureDispatcher(this, webServiceDispatcherProperties, dispatch.getRequestContext());

        SOAPBinding soapBinding = (SOAPBinding) dispatch.getBinding();

        if (webServiceDispatcherProperties.isUseAuthentication()) {
            String currentUsername = dispatchContainer.getCurrentUsername();
            String currentPassword = dispatchContainer.getCurrentPassword();

            dispatch.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, currentUsername);
            dispatch.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, currentPassword);
            logger.debug("Using authentication: username=" + currentUsername + ", password length="
                    + currentPassword.length());
        }

        // See: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
        String soapAction = webServiceDispatcherProperties.getSoapAction();

        if (StringUtils.isNotEmpty(soapAction)) {
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, true); // MIRTH-2109
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
        }

        // Get default headers
        Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>(
                dispatchContainer.getDefaultRequestHeaders());

        // Add custom headers
        if (MapUtils.isNotEmpty(webServiceDispatcherProperties.getHeaders())) {
            for (Entry<String, List<String>> entry : webServiceDispatcherProperties.getHeaders().entrySet()) {
                List<String> valueList = requestHeaders.get(entry.getKey());

                if (valueList == null) {
                    valueList = new ArrayList<String>();
                    requestHeaders.put(entry.getKey(), valueList);
                }

                valueList.addAll(entry.getValue());
            }
        }

        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);

        // build the message
        logger.debug("Creating SOAP envelope.");
        AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider();
        String content = attachmentHandlerProvider.reAttachMessage(webServiceDispatcherProperties.getEnvelope(),
                connectorMessage);
        Source source = new StreamSource(new StringReader(content));
        SOAPMessage message = soapBinding.getMessageFactory().createMessage();
        message.getSOAPPart().setContent(source);

        if (webServiceDispatcherProperties.isUseMtom()) {
            soapBinding.setMTOMEnabled(true);

            List<String> attachmentIds = webServiceDispatcherProperties.getAttachmentNames();
            List<String> attachmentContents = webServiceDispatcherProperties.getAttachmentContents();
            List<String> attachmentTypes = webServiceDispatcherProperties.getAttachmentTypes();

            for (int i = 0; i < attachmentIds.size(); i++) {
                String attachmentContentId = attachmentIds.get(i);
                String attachmentContentType = attachmentTypes.get(i);
                String attachmentContent = attachmentHandlerProvider.reAttachMessage(attachmentContents.get(i),
                        connectorMessage);

                AttachmentPart attachment = message.createAttachmentPart();
                attachment.setBase64Content(new ByteArrayInputStream(attachmentContent.getBytes("UTF-8")),
                        attachmentContentType);
                attachment.setContentId(attachmentContentId);
                message.addAttachmentPart(attachment);
            }
        }

        message.saveChanges();

        if (StringUtils.isNotBlank(webServiceDispatcherProperties.getLocationURI())) {
            dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                    webServiceDispatcherProperties.getLocationURI());
        }

        boolean redirect = false;
        int tryCount = 0;

        /*
         * Attempt the invocation until we hit the maximum allowed redirects. The redirections
         * we handle are when the scheme changes (i.e. from HTTP to HTTPS).
         */
        do {
            redirect = false;
            tryCount++;

            try {
                DispatchTask<SOAPMessage> task = new DispatchTask<SOAPMessage>(dispatch, message,
                        webServiceDispatcherProperties.isOneWay());
                SOAPMessage result;

                /*
                 * If the timeout is set to zero, we need to do the invocation in a separate
                 * thread. This is because there's no way to get a reference to the underlying
                 * JAX-WS socket, so there's no way to forcefully halt the dispatch. If the
                 * socket is truly hung and the user halts the channel, the best we can do is
                 * just interrupt and ignore the thread. This means that a thread leak is
                 * potentially introduced, so we need to notify the user appropriately.
                 */
                if (timeout == 0) {
                    // Submit the task to an executor so that it's interruptible
                    Future<SOAPMessage> future = executor.submit(task);
                    // Keep track of the task by adding it to our set
                    dispatchTasks.add(task);
                    result = future.get();
                } else {
                    // Call the task directly
                    result = task.call();
                }

                if (webServiceDispatcherProperties.isOneWay()) {
                    responseStatusMessage = "Invoked one way operation successfully.";
                } else {
                    responseData = sourceToXmlString(result.getSOAPPart().getContent());
                    responseStatusMessage = "Invoked two way operation successfully.";
                }
                logger.debug("Finished invoking web service, got result.");

                // Automatically accept message; leave it up to the response transformer to find SOAP faults
                responseStatus = Status.SENT;
            } catch (Throwable e) {
                // Unwrap the exception if it came from the executor
                if (e instanceof ExecutionException && e.getCause() != null) {
                    e = e.getCause();
                }

                // If the dispatch was interrupted, make sure to reset the interrupted flag
                if (e instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }

                Integer responseCode = null;
                String location = null;

                if (dispatch.getResponseContext() != null) {
                    responseCode = (Integer) dispatch.getResponseContext()
                            .get(MessageContext.HTTP_RESPONSE_CODE);

                    Map<String, List<String>> headers = (Map<String, List<String>>) dispatch
                            .getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);
                    if (MapUtils.isNotEmpty(headers)) {
                        List<String> locations = headers.get("Location");
                        if (CollectionUtils.isNotEmpty(locations)) {
                            location = locations.get(0);
                        }
                    }
                }

                if (tryCount < MAX_REDIRECTS && responseCode != null && responseCode >= 300
                        && responseCode < 400 && StringUtils.isNotBlank(location)) {
                    redirect = true;

                    // Replace the endpoint with the redirected URL
                    dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, location);
                } else {
                    // Leave the response status as QUEUED for NoRouteToHostException and ConnectException, otherwise ERROR
                    if (e instanceof NoRouteToHostException
                            || ((e.getCause() != null) && (e.getCause() instanceof NoRouteToHostException))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("HTTP transport error",
                                e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "HTTP transport error", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "HTTP transport error.", e));
                    } else if ((e.getClass() == ConnectException.class) || ((e.getCause() != null)
                            && (e.getCause().getClass() == ConnectException.class))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Connection refused.",
                                e);
                        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR,
                                getDestinationName(), connectorProperties.getName(), "Connection refused.", e));
                    } else {
                        if (e instanceof SOAPFaultException) {
                            try {
                                responseData = new DonkeyElement(((SOAPFaultException) e).getFault()).toXml();
                            } catch (DonkeyElementException e2) {
                            }
                        }
                        responseStatus = Status.ERROR;
                        responseStatusMessage = ErrorMessageBuilder
                                .buildErrorResponse("Error invoking web service", e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "Error invoking web service", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "Error invoking web service.", e));
                    }
                }
            }
        } while (redirect && tryCount < MAX_REDIRECTS);
    } catch (Exception e) {
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error creating web service dispatch",
                e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error creating web service dispatch", e);
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error creating web service dispatch.", e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation/*from   ww w. j a v  a  2  s  .c  o m*/
 * <I>modifyRecord(User,Owner,Collection,Record) : void</I>
 *
 * @param r the Record to modify
 * @param vAttachments a Vector containing the Attachments of the Record
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void modifyRecord(Record r, Vector vAttachments) throws Exception {
    User u = new User(getUserId());

    Collection c = new Collection("");

    c.setName(collection);

    try {
        smRequest = mf.createMessage();

        SOAPBodyElement sbeRequest = setRequestName(smRequest, "modifyRecord");

        addParam(sbeRequest, u);
        if (owner != null) {
            Owner oRequest = new Owner(owner);
            addParam(sbeRequest, oRequest);
        }
        addParam(sbeRequest, c);
        addParam(sbeRequest, r);

        for (int i = 0; i < vAttachments.size(); i++) {

            FileItem fi = (FileItem) vAttachments.get(i);

            String sNomFitxer = Utils.getFileName(fi.getName());

            File fTemp = File.createTempFile("attach", null);

            fi.write(fTemp);

            URL urlFile = new URL("file://" + fTemp.getPath());

            AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

            String fieldName = fi.getFieldName();

            ap.setContentId(fieldName + "/" + sNomFitxer);

            smRequest.addAttachmentPart(ap);
        }

        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "modify");
        } else {

        }
    } catch (SOAPException se) {
        throw se;
    }
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation//from w  w  w .  j  ava 2  s  .c  o m
 * <I>addRecord(User,Owner,Collection,Record) : void</I>
 *
 * @param r the Record to add
 * @param vAttachments a Vector containing the Attachments of the Record
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void addRecord(Record r, Vector vAttachments) throws Exception {
    User u = new User(getUserId());
    Collection c = new Collection("");

    Vector vTempFiles = new Vector();

    c.setName(collection);

    try {
        smRequest = mf.createMessage();

        SOAPBodyElement sbeRequest = setRequestName(smRequest, "addRecord");

        addParam(sbeRequest, u);
        if (owner != null) {
            Owner oRequest = new Owner(owner);
            addParam(sbeRequest, oRequest);
        }
        addParam(sbeRequest, c);
        addParam(sbeRequest, r);

        for (int i = 0; i < vAttachments.size(); i++) {

            FileItem fi = (FileItem) vAttachments.get(i);

            String sNomFitxer = Utils.getFileName(fi.getName());

            File fTemp = File.createTempFile("attach", null);

            fi.write(fTemp);

            vTempFiles.add(fTemp);

            URL urlFile = new URL("file://" + fTemp.getPath());

            AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

            String fieldName = fi.getFieldName();

            ap.setContentId(fieldName + "/" + sNomFitxer);

            smRequest.addAttachmentPart(ap);
        }
        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "add");
        } else {

        }
    } catch (Exception e) {
        throw e;
    } finally {
        File fAux;

        for (int i = 0; i < vTempFiles.size(); i++) {
            fAux = (File) vTempFiles.get(i);
            fAux.delete();
        }
    }
}