Example usage for javax.activation DataHandler getInputStream

List of usage examples for javax.activation DataHandler getInputStream

Introduction

In this page you can find the example usage for javax.activation DataHandler getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Get the InputStream for this object.

Usage

From source file:test.integ.be.e_contract.mycarenet.ehbox.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*from  w  w  w.j a v  a2s.  c o  m*/
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvokePlainText() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] data = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(data);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*from   ww w .j a v  a  2s  . c  o m*/
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvokePlainText() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] data = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(data);
    publicationDocument.setEncryptableBinaryContent(null);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*from ww w.  jav a2s . co m*/
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvoke() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] data = new byte[1024 * 256];
    for (int idx = 0; idx < data.length; idx++) {
        data[idx] = 'X';
    }
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:ro.cs.ts.web.servlet.ReportServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("doPost START");
    ServletOutputStream sos = response.getOutputStream();
    try {//retrieve the params from the context
        //         ***********************************************************************
        //Servlet's OutputStream
        //get the report type
        String reportType = request.getParameter(IConstant.REPORT_TYPE);
        logger.debug("Report type: " + reportType);

        String uid = (String) request.getParameter(IConstant.REPORT_UID);
        logger.debug("Retrieved UID in  report servlet: " + uid);
        Map<String, ReportParams> reportParamsMap = (Map<String, ReportParams>) TSContext
                .getFromContext(IConstant.REPORT_PARAM_MAP);
        ReportParams reportParams = reportParamsMap.get(uid);

        String format = (String) reportParams.getProperties()
                .get(IConstant.TS_PROJECT_REPORT_SEARCH_CRITERIA_FORMAT);
        // we set the is embeddable attribute
        if (format.toLowerCase().equals("html")
                && ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) == null) {
            logger.debug("The report is HTML embeddable");
            reportParams.setProperty(IConstant.TS_PROJECT_REPORT_IS_EMBEDDABLE, true);
        } else {// w w  w  .j  a  v  a  2  s  . c o m
            reportParams.setProperty(IConstant.TS_PROJECT_REPORT_IS_EMBEDDABLE, false);
        }

        logger.debug(ReportsMessageTools.viewReportParams(reportParams));

        DataHandler reportFileReceived = null;
        String reportTitle = null;
        if (reportType.equals(IConstant.REPORT_TYPE_PROJECT)) {
            logger.debug("Retrieving project report:  ");
            reportFileReceived = ReportsWebServiceClient.getInstance().getProjectReport(reportParams);
            reportTitle = (String) reportParams.getProperties()
                    .get(IConstant.TS_PROJECT_REPORT_REPORT_TITLE_PARAM);
        } else if (reportType.equals(IConstant.REPORT_TYPE_TIME_SHEET)) {
            logger.debug("Retrieving time sheet report:  ");
            reportFileReceived = ReportsWebServiceClient.getInstance().getTimeSheetReport(reportParams);
            reportTitle = (String) reportParams.getProperties()
                    .get(IConstant.TS_TIME_SHEET_REPORT_REPORT_TITLE_PARAM);
        } else {
            logger.error("We do not have a report type on the request!!!!");
            throw new BusinessException(ICodeException.REPORT_CREATE, null);
        }

        //set the response content type
        if (format.toLowerCase().equals("html")) {
            response.setContentType("text/html");
            if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"".concat(reportTitle).concat(".html\""));
            } else {
                response.setHeader("Content-Disposition",
                        "inline; filename=\"".concat(reportTitle).concat(".html\""));
            }
        } else if (format.toLowerCase().equals("pdf")) {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition",
                    "inline; filename=\"".concat(reportTitle).concat(".pdf\""));
        } else if (format.toLowerCase().equals("doc")) {
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".doc\""));
        } else if (format.toLowerCase().equals("xls")) {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".xls\""));
        }

        //write the received report bytes stream to response output stream
        byte buffer[] = new byte[4096];
        BufferedInputStream bis = new BufferedInputStream(reportFileReceived.getInputStream());

        int size = 0;
        int i;
        while ((i = bis.read(buffer, 0, 4096)) != -1) {
            sos.write(buffer, 0, i);
            size += i;
        }

        if (size == 0) {
            response.setContentType("text/plain");
            sos.write("No content !".getBytes());
        }

        bis.close();
        response.setContentLength(size);

        logger.debug("**** report transfer completed !");
    } catch (Exception ex) {
        logger.error("", ex);
        response.setContentType("text/html");
        String exceptionCode = ICodeException.REPORT_CREATE;

        sos.write(("<html xmlns=\"http://www.w3.org/1999/xhtml\">"
                + "<head>   <script type=\"text/javascript\" src=\"js/cs/cs_common.js\"></script>"
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/style.css\"/> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/fonts-min.css\" /> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/container.css\" /> </head> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/button.css\" />"
                + "<body> <div id=\"errorsContainer\" class=\"errorMessagesDiv\"> "
                + "<table class=\"errorMessagesTable\">" + "<tr>" + "<td>" + "</td>" + "<td>"
                + "<div class=\"hd\">" + "<div id=\"closeErrors\" class=\"messagesCloseButon\"></div>"
                + "</div>" + "</td>" + "</tr>" + "<tr>" + "<td>" + "<div class=\"bd\">"
                + "<div style=\"width:470px\"> "
                + messageSource.getMessage(CREATE_ERROR,
                        new Object[] { exceptionCode, ControllerUtils.getInstance().getFormattedCurrentTime() },
                        (Locale) request.getSession()
                                .getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME))
                + "<br/> " + "</div>" + "</div>" + "</td>" + "<td>" + "</td>" + "</tr>" + "</table>"
                + "<div class=\"ft\">&nbsp;</div>" + "</div>" + "<script> "
                + "if(typeof(YAHOO.widget.Module) != \"undefined\") { "
                + "YAHOO.ts.errorsContainer = new YAHOO.widget.Module(\"errorsContainer\", {visible:true} ); "
                + "YAHOO.ts.errorsContainer.render() ;" + "YAHOO.ts.errorsContainer.show();"
                + "YAHOO.util.Event.addListener(\"closeErrors\", \"click\", function () {   "
                + "YAHOO.ts.errorsContainer.hide();" + "YAHOO.ts.errorsContainer.destroy(); "
                + "}, YAHOO.ts.errorsContainer, true);" + "}" + "</script> </body></html>").getBytes());
    } finally {
        if (sos != null) {
            //Flushing and Closing OutputStream
            sos.flush();
            sos.close();
            logger.debug("**** servlet output stream closed.");
        }
    }
    logger.debug("doPost END");
}

From source file:org.bimserver.webservices.Service.java

@Override
public Integer checkin(final Long poid, final String comment, String deserializerName, Long fileSize,
        DataHandler dataHandler, Boolean merge, Boolean sync) throws ServerException, UserException {
    requireAuthenticationAndRunningServer();
    final DatabaseSession session = bimServer.getDatabase().createSession();
    String username = "Unknown";
    String userUsername = "Unknown";
    try {//  w  w  w .  j a v  a  2 s.co  m
        User user = (User) session.get(StorePackage.eINSTANCE.getUser(), currentUoid, false, null);
        username = user.getName();
        userUsername = user.getUsername();
    } finally {
        session.close();
    }
    try {
        File homeDirIncoming = new File(bimServer.getHomeDir(), "incoming");
        if (!homeDirIncoming.isDirectory()) {
            homeDirIncoming.mkdir();
        }
        File userDirIncoming = new File(homeDirIncoming, userUsername);
        if (!userDirIncoming.exists()) {
            userDirIncoming.mkdir();
        }
        InputStream inputStream = null;
        String fileName = dataHandler.getName();
        if (fileName == null || fileName.trim().equals("")) {
            inputStream = dataHandler.getInputStream();
        } else {
            if (fileName.contains("/")) {
                fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            }
            if (fileName.contains("\\")) {
                fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
            }
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            fileName = dateFormat.format(new Date()) + "-" + fileName;
            File file = new File(userDirIncoming, fileName);
            inputStream = new MultiplexingInputStream(dataHandler.getInputStream(), new FileOutputStream(file));
        }
        try {
            EmfDeserializer deserializer = bimServer.getEmfDeserializerFactory()
                    .createDeserializer(deserializerName);
            if (deserializer == null) {
                throw new UserException("Deserializer " + deserializerName + " not found");
            }
            try {
                deserializer.init(bimServer.getPluginManager().requireSchemaDefinition());
            } catch (PluginException e) {
                throw new UserException(e);
            }
            IfcModelInterface model = deserializer.read(inputStream, fileName, false, fileSize);
            if (model.size() == 0) {
                throw new DeserializeException("Cannot checkin empty model");
            }
            CheckinDatabaseAction checkinDatabaseAction = new CheckinDatabaseAction(bimServer, null,
                    accessMethod, poid, currentUoid, model, comment, merge, true);
            LongCheckinAction longAction = new LongCheckinAction(bimServer, username, userUsername, currentUoid,
                    checkinDatabaseAction);
            bimServer.getLongActionManager().start(longAction);
            if (sync) {
                longAction.waitForCompletion();
            }
            return longAction.getId();
        } catch (UserException e) {
            throw e;
        } catch (DeserializeException e) {
            throw new UserException(e);
        } finally {
            inputStream.close();
        }
    } catch (UserException e) {
        throw e;
    } catch (Throwable e) {
        LOGGER.error("", e);
        throw new ServerException(e);
    } finally {
        session.close();
    }
}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasicPlus.CatBasicPlusControllerImpl.java

public void exportarLomes(ActionMapping mapping, ExportarLomesForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    ///*from w w  w.j a  v a 2 s . c  om*/
    // This method is called after the LOM has been validated and exports
    // the LOM file content directly to the browser
    //

    CatalogadorBPSession os = this.getCatalogadorBPSession(request);
    final int BUFFER_SIZE = 2048;

    DataHandler dh = null;
    try {

        // Remember: grab the LOM from the disk so that we don't have any of the temporary fields
        // that may have been added to accept user input.
        LomAvanzadoVO lomAdvanced = this.getSrvCatalogacionAvanzadaService()
                .obtenerLomAvanzado(os.getIdentificador(), os.getUsuario(), os.getIdioma());

        dh = this.getSrvCatalogacionAvanzadaService().exportarLomes(os.getIdentificador(), os.getUsuario(),
                lomAdvanced, os.getIdioma());

    } catch (Exception e) {
        logger.error(e);
        throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
    }

    if (dh == null) {
        logger.error("Fichero  vacio. Abortamos descarga.");
        throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
    }

    //        asignamos el titulo del fichero que vamos a exportar

    response.setContentType("text/xml;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename=metadataLOMES.xml");
    OutputStream out = response.getOutputStream();
    InputStream in = dh.getInputStream();
    logger.debug("Descargando metadata.xml");
    byte[] buffer = new byte[BUFFER_SIZE];
    int count;
    while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
        out.write(buffer, 0, count);
    }

    out.flush();
}

From source file:org.bimserver.webservices.impl.ServiceImpl.java

@Override
public Long checkinInitiated(Long topicId, final Long poid, final String comment, Long deserializerOid,
        Long fileSize, String fileName, DataHandler dataHandler, Boolean merge, Boolean sync)
        throws ServerException, UserException {
    requireAuthenticationAndRunningServer();
    final DatabaseSession session = getBimServer().getDatabase().createSession();
    String username = "Unknown";
    String userUsername = "Unknown";
    try {//w  w w.  j  a v a  2 s.c o m
        User user = (User) session.get(StorePackage.eINSTANCE.getUser(), getAuthorization().getUoid(),
                OldQuery.getDefault());
        Project project = session.get(poid, OldQuery.getDefault());
        if (project == null) {
            throw new UserException("No project found with poid " + poid);
        }
        username = user.getName();
        userUsername = user.getUsername();
        Path homeDirIncoming = getBimServer().getHomeDir().resolve("incoming");
        Path userDirIncoming = homeDirIncoming.resolve(userUsername);
        if (!Files.exists(userDirIncoming)) {
            Files.createDirectories(userDirIncoming);
        }
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        if (fileName.contains("\\")) {
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String cacheFileName = dateFormat.format(new Date()) + "-" + fileName;
        Path file = userDirIncoming.resolve(cacheFileName);
        return checkinInternal(topicId, poid, comment, deserializerOid, fileSize, fileName,
                dataHandler.getInputStream(), merge, sync, session, username, userUsername, project, file);
    } catch (UserException e) {
        throw e;
    } catch (Throwable e) {
        LOGGER.error("", e);
        throw new ServerException(e);
    } finally {
        session.close();
    }
}

From source file:com.collabnet.ccf.pi.cee.pt.v50.ProjectTrackerReader.java

@Override
public List<GenericArtifact> getArtifactAttachments(Document syncInfo, GenericArtifact artifactData) {
    String artifactId = artifactData.getSourceArtifactId();
    String artifactIdentifier = artifactId.substring(artifactId.lastIndexOf(":") + 1);
    Date lastModifiedDate = this.getLastModifiedDate(syncInfo);
    long fromTime = lastModifiedDate.getTime();
    // long toTime = System.currentTimeMillis();
    TrackerArtifactType trackerArtifactType = this.getTrackerArtifactTypeForArtifactId(syncInfo, artifactId);
    ArtifactType[] ata = new ArtifactType[1];
    ata[0] = new ArtifactType(trackerArtifactType.getTagName(), trackerArtifactType.getNamespace(),
            trackerArtifactType.getDisplayName());
    ArrayList<GenericArtifact> attachmentGAs = new ArrayList<GenericArtifact>();
    TrackerWebServicesClient twsclient = null;

    try {//from  w  w w  . j  av a 2  s  .c  om
        twsclient = this.getConnection(syncInfo);
        ArtifactHistoryList ahl = ProjectTrackerReader.artifactHistoryList.get();
        History historyList[] = null;
        if (ahl != null)
            historyList = ahl.getHistory();
        if (historyList != null) {
            for (History history : historyList) {
                HistoryTransaction[] transactions = history.getHistoryTransaction();
                int transactionsCount = transactions == null ? 0 : transactions.length;
                for (int i = 0; i < transactionsCount; i++) {
                    HistoryTransaction ht = transactions[i];
                    String modifiedBy = ht.getModifiedBy();
                    if ((!getConnectorUserDisplayName().equals(modifiedBy) || !isIgnoreConnectorUserUpdates())
                            && (!modifiedBy.equals(
                                    getResyncUserDisplayName() == null ? "" : getResyncUserDisplayName())
                                    || !isIgnoreConnectorUserUpdates())
                            && ht.getModifiedOn() > fromTime) {
                        HistoryActivity[] haa = ht.getHistoryActivity();
                        for (HistoryActivity ha : haa) {
                            String historyArtifactId = ha.getArtifactId();
                            if (historyArtifactId.equals(artifactIdentifier)) {
                                if (ha.getTagName().equals(ATTACHMENT_TAG_NAME)) {
                                    if (ha.getType().equals(ATTACHMENT_ADDED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getNewValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (attachmentId == null || attachmentIDNameMap == null)
                                                continue;

                                            String attachmentName = null;
                                            String attachmentDescription = null;
                                            ClientArtifactAttachment attachment = attachmentIDNameMap
                                                    .get(attachmentId);
                                            if (attachment == null) {
                                                log.warn("Attachment with id " + attachmentId
                                                        + " does not exist!");
                                                continue;
                                            }
                                            attachmentName = attachment.getAttachmentName();
                                            attachmentDescription = attachment.getDescription();
                                            if (StringUtils.isEmpty(attachmentName)) {
                                                attachmentName = "PT-Attachment" + attachmentId + ".file";
                                                log.warn(
                                                        "Could not determine attachment name for attachment id "
                                                                + attachmentId);
                                            }

                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.CREATE);
                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());
                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());
                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.DATA);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            GenericArtifactField sourceURLField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_SOURCE_URL,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            sourceURLField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.LINK);
                                            sourceURLField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            sourceURLField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField nameField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_NAME,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            nameField.setFieldValue(attachmentName);
                                            nameField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            nameField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField descriptionField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_DESCRIPTION,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            descriptionField.setFieldValue(attachmentDescription);
                                            descriptionField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            descriptionField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField mimeTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_MIME_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            mimeTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            mimeTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            long size = 0;
                                            DataHandler handler = null;
                                            try {
                                                handler = twsclient.getDataHandlerForAttachment(
                                                        artifactIdentifier, attachmentId);
                                            } catch (WSException e) {
                                                int code = e.getCode();
                                                if (code == 214) {
                                                    continue;
                                                } else
                                                    throw e;
                                            }
                                            String contentType = handler.getContentType();
                                            mimeTypeField.setFieldValue(contentType);
                                            String axisFileName = handler.getName();
                                            File attachmentAxisFile = new File(axisFileName);
                                            size = attachmentAxisFile.length();
                                            long maxAttachmentSize = this.getMaxAttachmentSizePerArtifact();
                                            if (size > maxAttachmentSize) {
                                                log.warn("Attachment " + attachmentName + " is of size " + size
                                                        + " bytes."
                                                        + " This is more than the configured maximum attachment size"
                                                        + " that can be shipped in an artifact");
                                                continue;
                                            }
                                            if (!this.isShipAttachmentsWithArtifact()) {
                                                File tempFile = null;
                                                FileOutputStream fos = null;
                                                FileInputStream fis = null;
                                                try {
                                                    if (attachmentAxisFile.exists()) {
                                                        byte[] bytes = new byte[1024 * 3];
                                                        tempFile = File.createTempFile("PT_Attachment",
                                                                ".file");

                                                        String attachmentDataFile = tempFile.getAbsolutePath();
                                                        int readBytes = 0;
                                                        fos = new FileOutputStream(tempFile);
                                                        fis = new FileInputStream(attachmentAxisFile);
                                                        while ((readBytes = fis.read(bytes)) != -1) {
                                                            fos.write(bytes, 0, readBytes);
                                                        }
                                                        fos.close();
                                                        GenericArtifactField attachmentDataFileField = ga
                                                                .addNewField(
                                                                        AttachmentMetaData.ATTACHMENT_DATA_FILE,
                                                                        GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                                        attachmentDataFileField.setFieldValueType(
                                                                GenericArtifactField.FieldValueTypeValue.STRING);
                                                        attachmentDataFileField
                                                                .setFieldValue(attachmentDataFile);
                                                        attachmentDataFileField.setFieldAction(
                                                                GenericArtifactField.FieldActionValue.REPLACE);
                                                        bytes = null;
                                                    }
                                                } catch (IOException e) {
                                                    String message = "Could not write attachment content to temp file."
                                                            + " Shipping the attachment with the artifact.";
                                                    log.error(message, e);
                                                    throw new CCFRuntimeException(message, e);
                                                } finally {
                                                    if (fis != null) {
                                                        try {
                                                            fis.close();
                                                        } catch (IOException e) {
                                                            log.warn("Could not close input stream for "
                                                                    + attachmentAxisFile.getAbsolutePath());
                                                        }
                                                    }
                                                    if (fos != null) {
                                                        try {
                                                            fos.close();
                                                        } catch (IOException e) {
                                                            String filename = "";
                                                            if (tempFile != null) {
                                                                filename = tempFile.getAbsolutePath();
                                                            }
                                                            log.warn("Could not close output stream for "
                                                                    + filename);
                                                        }
                                                    }
                                                }
                                            } else {
                                                InputStream is = handler.getInputStream();
                                                byte[] bytes = new byte[(int) size];
                                                is.read(bytes);
                                                is.close();
                                                ga.setRawAttachmentData(bytes);
                                            }
                                            GenericArtifactField sizeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_SIZE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            sizeField.setFieldValue(size);
                                            sizeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            sizeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    } else if (ha.getType().equals(ATTACHMENT_DELETED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getOldValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (attachmentId == null)
                                                continue;
                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.DELETE);
                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());
                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());
                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.DATA);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    } else if (ha.getType().equals(URL_ADDED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getNewValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (linkIDNameMap == null || linkIDNameMap.size() == 0)
                                                continue;
                                            Set<Entry<String, ClientArtifactAttachment>> linkIDEntry = linkIDNameMap
                                                    .entrySet();
                                            Iterator<Entry<String, ClientArtifactAttachment>> linkEntryIt = linkIDEntry
                                                    .iterator();
                                            String attachmentName = null;
                                            String attachmentDescription = null;
                                            if (linkEntryIt.hasNext()) {
                                                Entry<String, ClientArtifactAttachment> entry = linkEntryIt
                                                        .next();
                                                ClientArtifactAttachment clientArtifactAttachment = entry
                                                        .getValue();
                                                attachmentName = clientArtifactAttachment.getAttachmentName();
                                                attachmentDescription = clientArtifactAttachment
                                                        .getDescription();
                                                attachmentId = entry.getKey();
                                            }

                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.CREATE);

                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());

                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());

                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.LINK);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            GenericArtifactField sourceURLField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_SOURCE_URL,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            sourceURLField.setFieldValue(attachmentName);
                                            sourceURLField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            sourceURLField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField descriptionField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_DESCRIPTION,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            descriptionField.setFieldValue(attachmentDescription);
                                            descriptionField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            descriptionField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField nameField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_NAME,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            nameField.setFieldValue(attachmentName);
                                            nameField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            nameField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    } else if (ha.getType().equals(URL_DELETED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getOldValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (attachmentId == null)
                                                continue;
                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.DELETE);
                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());

                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());
                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.DATA);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Exception while getting the attachment data";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } finally {
        ProjectTrackerReader.artifactHistoryList.set(null);
        this.attachmentIDNameMap = null;
        this.linkIDNameMap = null;
        if (twsclient != null) {
            getConnectionManager().releaseConnection(twsclient);
            twsclient = null;
        }
    }
    return attachmentGAs;
}