Example usage for javax.activation DataHandler getContent

List of usage examples for javax.activation DataHandler getContent

Introduction

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

Prototype

public Object getContent() throws IOException 

Source Link

Document

Return the data in its preferred Object form.

Usage

From source file:se.inera.axel.shs.camel.CamelShsDataPartConverterTest.java

@DirtiesContext
@Test//w w w. java2  s.  co  m
public void convertCamelMessageToDataPartWithFilenameInContentType() throws Exception {

    resultEndpoint.expectedMessageCount(1);

    String message = DEFAULT_TEST_BODY;

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, DEFAULT_TEST_DATAPART_TRANSFERENCODING);
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE,
            DEFAULT_TEST_DATAPART_CONTENTTYPE + ";name=" + DEFAULT_TEST_DATAPART_FILENAME);
    headers.put(ShsHeaders.DATAPART_CONTENTLENGTH, message.length());
    headers.put(ShsHeaders.DATAPART_TYPE, DEFAULT_TEST_DATAPART_TYPE);

    template.sendBodyAndHeaders("direct:camelToShsConverter", message, headers);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();
    DataPart datapart = in.getMandatoryBody(DataPart.class);
    assertNotNull(datapart);

    assertEquals((long) datapart.getContentLength(), message.length());
    assertEquals(datapart.getContentType(),
            DEFAULT_TEST_DATAPART_CONTENTTYPE + ";name=" + DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(datapart.getDataPartType(), DEFAULT_TEST_DATAPART_TYPE);
    assertEquals(datapart.getFileName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(datapart.getTransferEncoding(), DEFAULT_TEST_DATAPART_TRANSFERENCODING);

    assertNotNull(datapart.getDataHandler());
    DataHandler dataHandler = datapart.getDataHandler();
    assertEquals(dataHandler.getContentType(),
            DEFAULT_TEST_DATAPART_CONTENTTYPE + ";name=" + DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(dataHandler.getName(), DEFAULT_TEST_DATAPART_FILENAME);
    assertEquals(dataHandler.getContent(), DEFAULT_TEST_BODY);

}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * This wrapper is used to work around a bug in the sun io inside
 * sun.io.ByteToCharConverter.getConverterClass(). The programmer uses a
 * cute coding trick that appends the charset to a prefix to create a
 * Class name that they then attempt to load. The problem is that if the
 * charset is not one that they "recognize", and the name has something
 * like a dash character in it, the resulting Class name has an invalid
 * character in it. This results in an IllegalArgumentException instead of
 * the UnsupportedEncodingException that is documented. Thus, we need to
 * catch the undocumented exception.//from   www  .  j  a v  a2s  . c o m
 *
 * @param dh The DataHandler from which to get the content.
 *
 * @return The content.
 *
 * @exception MessagingException if the content charset is unsupported.
 */
public static Object getDataHandlerContent(DataHandler dh) throws MessagingException {
    Object result = null;

    try {
        result = dh.getContent();
    } catch (IllegalArgumentException ex) {
        throw new MessagingException("content charset is not recognized: " + ex.getMessage());
    } catch (IOException ex) {
        throw new MessagingException("getDataHandlerContent(): " + ex.getMessage());
    }

    return result;
}

From source file:org.apache.axis.encoding.ser.PlainTextDataHandlerDeserializer.java

public void startElement(String namespace, String localName, String prefix, Attributes attributes,
        DeserializationContext context) throws SAXException {

    super.startElement(namespace, localName, prefix, attributes, context);

    if (getValue() instanceof DataHandler) {
        try {/*from  w  w  w .  ja v a  2 s . c  o m*/
            DataHandler dh = (DataHandler) getValue();
            setValue(dh.getContent());
        } catch (IOException ioe) {
        }
    }
}

From source file:org.apache.axis.utils.JavaUtils.java

/** Utility function to convert an Object to some desired Class.
 *
 * Right now this works for:/*www.j  ava  2 s  .  c o  m*/
 *     arrays <-> Lists,
 *     Holders <-> held values
 * @param arg the array to convert
 * @param destClass the actual class we want
 */
public static Object convert(Object arg, Class destClass) {
    if (destClass == null) {
        return arg;
    }

    Class argHeldType = null;
    if (arg != null) {
        argHeldType = getHolderValueType(arg.getClass());
    }

    if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass())) {
        return arg;
    }

    if (log.isDebugEnabled()) {
        String clsName = "null";
        if (arg != null)
            clsName = arg.getClass().getName();
        log.debug(Messages.getMessage("convert00", clsName, destClass.getName()));
    }

    // See if a previously converted value is stored in the argument.
    Object destValue = null;
    if (arg instanceof ConvertCache) {
        destValue = ((ConvertCache) arg).getConvertedValue(destClass);
        if (destValue != null)
            return destValue;
    }

    // Get the destination held type or the argument held type if they exist
    Class destHeldType = getHolderValueType(destClass);

    // Convert between Axis special purpose HexBinary and byte[]
    if (arg instanceof HexBinary && destClass == byte[].class) {
        return ((HexBinary) arg).getBytes();
    } else if (arg instanceof byte[] && destClass == HexBinary.class) {
        return new HexBinary((byte[]) arg);
    }

    // Convert between Calendar and Date
    if (arg instanceof Calendar && destClass == Date.class) {
        return ((Calendar) arg).getTime();
    }
    if (arg instanceof Date && destClass == Calendar.class) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime((Date) arg);
        return calendar;
    }

    // Convert between Calendar and java.sql.Date
    if (arg instanceof Calendar && destClass == java.sql.Date.class) {
        return new java.sql.Date(((Calendar) arg).getTime().getTime());
    }

    // Convert between HashMap and Hashtable
    if (arg instanceof HashMap && destClass == Hashtable.class) {
        return new Hashtable((HashMap) arg);
    }

    // Convert an AttachmentPart to the given destination class.
    if (isAttachmentSupported()
            && (arg instanceof InputStream || arg instanceof AttachmentPart || arg instanceof DataHandler)) {
        try {
            String destName = destClass.getName();
            if (destClass == String.class || destClass == OctetStream.class || destClass == byte[].class
                    || destClass == Image.class || destClass == Source.class || destClass == DataHandler.class
                    || destName.equals("javax.mail.internet.MimeMultipart")) {
                DataHandler handler = null;
                if (arg instanceof AttachmentPart) {
                    handler = ((AttachmentPart) arg).getDataHandler();
                } else if (arg instanceof DataHandler) {
                    handler = (DataHandler) arg;
                }
                if (destClass == Image.class) {
                    // Note:  An ImageIO component is required to process an Image
                    // attachment, but if the image would be null
                    // (is.available == 0) then ImageIO component isn't needed
                    // and we can return null.
                    InputStream is = handler.getInputStream();
                    if (is.available() == 0) {
                        return null;
                    } else {
                        ImageIO imageIO = ImageIOFactory.getImageIO();
                        if (imageIO != null) {
                            return getImageFromStream(is);
                        } else {
                            log.info(Messages.getMessage("needImageIO"));
                            return arg;
                        }
                    }
                } else if (destClass == javax.xml.transform.Source.class) {
                    // For a reason unknown to me, the handler's
                    // content is a String.  Convert it to a
                    // StreamSource.
                    return new StreamSource(handler.getInputStream());
                } else if (destClass == OctetStream.class || destClass == byte[].class) {
                    InputStream in = null;
                    if (arg instanceof InputStream) {
                        in = (InputStream) arg;
                    } else {
                        in = handler.getInputStream();
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int byte1 = -1;
                    while ((byte1 = in.read()) != -1)
                        baos.write(byte1);
                    return new OctetStream(baos.toByteArray());
                } else if (destClass == DataHandler.class) {
                    return handler;
                } else {
                    return handler.getContent();
                }
            }
        } catch (IOException ioe) {
        } catch (SOAPException se) {
        }
    }

    // If the destination is an array and the source
    // is a suitable component, return an array with 
    // the single item.
    if (arg != null && destClass.isArray() && !destClass.getComponentType().equals(Object.class)
            && destClass.getComponentType().isAssignableFrom(arg.getClass())) {
        Object array = Array.newInstance(destClass.getComponentType(), 1);
        Array.set(array, 0, arg);
        return array;
    }

    // in case destClass is array and arg is ArrayOfT class. (ArrayOfT -> T[])
    if (arg != null && destClass.isArray()) {
        Object newArg = ArrayUtil.convertObjectToArray(arg, destClass);
        if (newArg == null || (newArg != ArrayUtil.NON_CONVERTABLE && newArg != arg)) {
            return newArg;
        }
    }

    // in case arg is ArrayOfT and destClass is an array. (T[] -> ArrayOfT)
    if (arg != null && arg.getClass().isArray()) {
        Object newArg = ArrayUtil.convertArrayToObject(arg, destClass);
        if (newArg != null)
            return newArg;
    }

    // Return if no conversion is available
    if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))
            && ((destHeldType == null && argHeldType == null)
                    || (destHeldType != null && argHeldType != null))) {
        return arg;
    }

    // Take care of Holder conversion
    if (destHeldType != null) {
        // Convert arg into Holder holding arg.
        Object newArg = convert(arg, destHeldType);
        Object argHolder = null;
        try {
            argHolder = destClass.newInstance();
            setHolderValue(argHolder, newArg);
            return argHolder;
        } catch (Exception e) {
            return arg;
        }
    } else if (argHeldType != null) {
        // Convert arg into the held type
        try {
            Object newArg = getHolderValue(arg);
            return convert(newArg, destClass);
        } catch (HolderException e) {
            return arg;
        }
    }

    // Flow to here indicates that neither arg or destClass is a Holder

    // Check to see if the argument has a prefered destination class.
    if (arg instanceof ConvertCache && ((ConvertCache) arg).getDestClass() != destClass) {
        Class hintClass = ((ConvertCache) arg).getDestClass();
        if (hintClass != null && hintClass.isArray() && destClass.isArray()
                && destClass.isAssignableFrom(hintClass)) {
            destClass = hintClass;
            destValue = ((ConvertCache) arg).getConvertedValue(destClass);
            if (destValue != null)
                return destValue;
        }
    }

    if (arg == null) {
        return arg;
    }

    // The arg may be an array or List 
    int length = 0;
    if (arg.getClass().isArray()) {
        length = Array.getLength(arg);
    } else {
        length = ((Collection) arg).size();
    }
    if (destClass.isArray()) {
        if (destClass.getComponentType().isPrimitive()) {

            Object array = Array.newInstance(destClass.getComponentType(), length);
            // Assign array elements
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    Array.set(array, i, Array.get(arg, i));
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    Array.set(array, idx++, i.next());
                }
            }
            destValue = array;

        } else {
            Object[] array;
            try {
                array = (Object[]) Array.newInstance(destClass.getComponentType(), length);
            } catch (Exception e) {
                return arg;
            }

            // Use convert to assign array elements.
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    array[i] = convert(Array.get(arg, i), destClass.getComponentType());
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    array[idx++] = convert(i.next(), destClass.getComponentType());
                }
            }
            destValue = array;
        }
    } else if (Collection.class.isAssignableFrom(destClass)) {
        Collection newList = null;
        try {
            // if we are trying to create an interface, build something
            // that implements the interface
            if (destClass == Collection.class || destClass == List.class) {
                newList = new ArrayList();
            } else if (destClass == Set.class) {
                newList = new HashSet();
            } else {
                newList = (Collection) destClass.newInstance();
            }
        } catch (Exception e) {
            // Couldn't build one for some reason... so forget it.
            return arg;
        }

        if (arg.getClass().isArray()) {
            for (int j = 0; j < length; j++) {
                newList.add(Array.get(arg, j));
            }
        } else {
            for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) {
                newList.add(j.next());
            }
        }
        destValue = newList;
    } else {
        destValue = arg;
    }

    // Store the converted value in the argument if possible.
    if (arg instanceof ConvertCache) {
        ((ConvertCache) arg).setConvertedValue(destClass, destValue);
    }
    return destValue;
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java

private static DataHandler createDataHandler(Object value, Class cls, String[] mimeTypes, String cid) {
    if (log.isDebugEnabled()) {
        System.out.println("Construct data handler for " + cls + " cid=" + cid);
    }//from ww w.  jav a2s  . c om
    DataHandler dh = null;
    if (cls.isAssignableFrom(DataHandler.class)) {
        dh = (DataHandler) value;
        if (dh == null) {
            return dh; //return if DataHandler is null
        }

        try {
            Object content = dh.getContent();
            // If the content is a Source, convert to a String due to 
            // problems with the DataContentHandler
            if (content instanceof Source) {
                if (log.isDebugEnabled()) {
                    System.out
                            .println("Converting DataHandler Source content to " + "DataHandlerString content");
                }
                byte[] bytes = (byte[]) ConvertUtils.convert(content, byte[].class);
                String newContent = new String(bytes);
                return new DataHandler(newContent, mimeTypes[0]);
            }
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    } else {
        try {
            byte[] bytes = createBytes(value, cls, mimeTypes);
            // Create MIME Body Part
            InternetHeaders ih = new InternetHeaders();
            ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeTypes[0]);
            MimeBodyPart mbp = new MimeBodyPart(ih, bytes);

            //Create a data source for the MIME Body Part
            MimePartDataSource ds = new MimePartDataSource(mbp);

            dh = new DataHandler(ds);
            mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }
    return dh;
}

From source file:org.iexhub.services.GetPatientDataService.java

@GET
@Path("/ccd")
@Produces({ MediaType.APPLICATION_JSON })
public Response getCCD(@Context HttpHeaders headers) {
    log.info("Entered getPatientData service");

    boolean tls = false;
    tls = (IExHubConfig.getProperty("XdsBRegistryEndpointURI") == null) ? false
            : ((IExHubConfig.getProperty("XdsBRegistryEndpointURI").toLowerCase().contains("https") ? true
                    : false));/* ww w.ja v a2s  .co  m*/
    GetPatientDataService.testMode = IExHubConfig.getProperty("TestMode", GetPatientDataService.testMode);
    GetPatientDataService.testJSONDocumentPathname = IExHubConfig.getProperty("TestJSONDocumentPathname",
            GetPatientDataService.testJSONDocumentPathname);
    GetPatientDataService.cdaToJsonTransformXslt = IExHubConfig.getProperty("CDAToJSONTransformXSLT",
            GetPatientDataService.cdaToJsonTransformXslt);
    GetPatientDataService.iExHubDomainOid = IExHubConfig.getProperty("IExHubDomainOID",
            GetPatientDataService.iExHubDomainOid);
    GetPatientDataService.iExHubAssigningAuthority = IExHubConfig.getProperty("IExHubAssigningAuthority",
            GetPatientDataService.iExHubAssigningAuthority);
    GetPatientDataService.xdsBRepositoryUniqueId = IExHubConfig.getProperty("XdsBRepositoryUniqueId",
            GetPatientDataService.xdsBRepositoryUniqueId);

    String retVal = "";
    GetPatientDataResponse patientDataResponse = new GetPatientDataResponse();
    DocumentsResponseDto documentsResponseDto = new DocumentsResponseDto();
    List<PatientDocument> patientDocuments = new ArrayList<>();

    if (!testMode) {
        try {
            if (xdsB == null) {
                log.info("Instantiating XdsB connector...");
                xdsB = new XdsB(null, null, tls);
                log.info("XdsB connector successfully started");
            }
        } catch (Exception e) {
            log.error("Error encountered instantiating XdsB connector, " + e.getMessage());
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }

        try {
            MultivaluedMap<String, String> headerParams = headers.getRequestHeaders();
            String ssoAuth = headerParams.getFirst("ssoauth");

            log.info("HTTP headers successfully retrieved");
            String[] splitPatientId = ssoAuth.split("&LastName=");
            String patientId = (splitPatientId[0].split("=").length == 2) ? splitPatientId[0].split("=")[1]
                    : null;

            String[] parts = splitPatientId[1].split("&");
            String lastName = (parts[0].length() > 0) ? parts[0] : null;
            String firstName = (parts[1].split("=").length == 2) ? parts[1].split("=")[1] : null;
            String middleName = (parts[2].split("=").length == 2) ? parts[2].split("=")[1] : null;
            String dateOfBirth = (parts[3].split("=").length == 2) ? parts[3].split("=")[1] : null;
            String gender = (parts[4].split("=").length == 2) ? parts[4].split("=")[1] : null;
            String motherMaidenName = (parts[5].split("=").length == 2) ? parts[5].split("=")[1] : null;
            String addressStreet = (parts[6].split("=").length == 2) ? parts[6].split("=")[1] : null;
            String addressCity = (parts[7].split("=").length == 2) ? parts[7].split("=")[1] : null;
            String addressState = (parts[8].split("=").length == 2) ? parts[8].split("=")[1] : null;
            String addressPostalCode = (parts[9].split("=").length == 2) ? parts[9].split("=")[1] : null;
            String otherIDsScopingOrganization = (parts[10].split("=").length == 2) ? parts[10].split("=")[1]
                    : null;
            String startDate = (parts[11].split("=").length == 2) ? parts[11].split("=")[1] : null;
            String endDate = (parts[12].split("=").length == 2) ? parts[12].split("=")[1] : null;

            log.info("HTTP headers successfully parsed, now calling XdsB registry...");

            // Determine if a complete patient ID (including OID and ISO specification) was provided.  If not, then append IExHubDomainOid and IExAssigningAuthority...
            if (!patientId.contains("^^^&")) {
                patientId = "'" + patientId + "^^^&" + GetPatientDataService.iExHubDomainOid + "&"
                        + GetPatientDataService.iExHubAssigningAuthority + "'";
            }

            AdhocQueryResponse registryResponse = xdsB.registryStoredQuery(patientId,
                    (startDate != null) ? DateFormat.getDateInstance().format(startDate) : null,
                    (endDate != null) ? DateFormat.getDateInstance().format(endDate) : null);

            log.info("Call to XdsB registry successful");

            // Determine if registry server returned any errors...
            if ((registryResponse.getRegistryErrorList() != null)
                    && (registryResponse.getRegistryErrorList().getRegistryError().length > 0)) {

                for (RegistryError_type0 error : registryResponse.getRegistryErrorList().getRegistryError()) {
                    StringBuilder errorText = new StringBuilder();
                    if (error.getErrorCode() != null) {
                        errorText.append("Error code=" + error.getErrorCode() + "\n");
                    }
                    if (error.getCodeContext() != null) {
                        errorText.append("Error code context=" + error.getCodeContext() + "\n");
                    }

                    // Error code location (i.e., stack trace) only to be logged to IExHub error file
                    patientDataResponse.getErrorMsgs().add(errorText.toString());

                    if (error.getLocation() != null) {
                        errorText.append("Error location=" + error.getLocation());
                    }
                    log.error(errorText.toString());
                }
            }

            // Try to retrieve documents...
            RegistryObjectListType registryObjectList = registryResponse.getRegistryObjectList();
            IdentifiableType[] documentObjects = registryObjectList.getIdentifiable();
            if ((documentObjects != null) && (documentObjects.length > 0)) {
                log.info("Documents found in the registry, retrieving them from the repository...");

                HashMap<String, String> documents = new HashMap<String, String>();
                for (IdentifiableType identifiable : documentObjects) {
                    if (identifiable.getClass().equals(ExtrinsicObjectType.class)) {
                        // Determine if the "home" attribute (homeCommunityId in XCA parlance) is present...
                        String home = ((((ExtrinsicObjectType) identifiable).getHome() != null)
                                && (((ExtrinsicObjectType) identifiable).getHome().getPath().length() > 0))
                                        ? ((ExtrinsicObjectType) identifiable).getHome().getPath()
                                        : null;

                        ExternalIdentifierType[] externalIdentifiers = ((ExtrinsicObjectType) identifiable)
                                .getExternalIdentifier();

                        // Find the ExternalIdentifier that has the "XDSDocumentEntry.uniqueId" value...
                        String uniqueId = null;
                        for (ExternalIdentifierType externalIdentifier : externalIdentifiers) {
                            String val = externalIdentifier.getName().getInternationalStringTypeSequence()[0]
                                    .getLocalizedString().getValue().getFreeFormText();
                            if ((val != null) && (val.compareToIgnoreCase("XDSDocumentEntry.uniqueId") == 0)) {
                                log.info("Located XDSDocumentEntry.uniqueId ExternalIdentifier, uniqueId="
                                        + uniqueId);
                                uniqueId = externalIdentifier.getValue().getLongName();
                                break;
                            }
                        }

                        if (uniqueId != null) {
                            documents.put(uniqueId, home);
                            log.info("Document ID added: " + uniqueId + ", homeCommunityId: " + home);
                        }
                    } else {
                        String home = ((identifiable.getHome() != null)
                                && (identifiable.getHome().getPath().length() > 0))
                                        ? identifiable.getHome().getPath()
                                        : null;
                        documents.put(identifiable.getId().getPath(), home);
                        log.info("Document ID added: " + identifiable.getId().getPath() + ", homeCommunityId: "
                                + home);
                    }
                }

                log.info("Invoking XdsB repository connector retrieval...");
                RetrieveDocumentSetResponse documentSetResponse = xdsB
                        .retrieveDocumentSet(xdsBRepositoryUniqueId, documents, patientId);
                log.info("XdsB repository connector retrieval succeeded");

                // Invoke appropriate map(s) to process documents in documentSetResponse...
                if (documentSetResponse.getRetrieveDocumentSetResponse()
                        .getRetrieveDocumentSetResponseTypeSequence_type0() != null) {
                    DocumentResponse_type0[] docResponseArray = documentSetResponse
                            .getRetrieveDocumentSetResponse().getRetrieveDocumentSetResponseTypeSequence_type0()
                            .getDocumentResponse();
                    if (docResponseArray != null) {
                        try {
                            for (DocumentResponse_type0 document : docResponseArray) {
                                log.info("Processing document ID="
                                        + document.getDocumentUniqueId().getLongName());

                                String mimeType = docResponseArray[0].getMimeType().getLongName();
                                if (mimeType.compareToIgnoreCase("text/xml") == 0) {
                                    DataHandler dh = document.getDocument();
                                    String documentStr = dh.getContent().toString();
                                    String documentName = document.getDocumentUniqueId().getLongName();
                                    PatientDocument patientDocument = new PatientDocument(documentName,
                                            documentStr);
                                    patientDocuments.add(patientDocument);
                                } else {
                                    patientDataResponse.getErrorMsgs()
                                            .add("Document retrieved is not XML - document ID="
                                                    + document.getDocumentUniqueId().getLongName());
                                }
                            }
                        } catch (Exception e) {
                            log.error("Error encountered, " + e.getMessage());
                            throw e;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Error encountered, " + e.getMessage());
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }
    } else {
        // Return test document when testMode is true
        try {
            retVal = FileUtils.readFileToString(new File(GetPatientDataService.testJSONDocumentPathname));
            return Response.status(Response.Status.OK).entity(retVal).type(MediaType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }
    }
    documentsResponseDto.setDocuments(patientDocuments);

    return Response.status(Response.Status.OK).entity(documentsResponseDto).type(MediaType.APPLICATION_JSON)
            .build();
}

From source file:org.sciflex.plugins.synapse.esper.mediators.helpers.EPLStatementHelper.java

/**
 * Changes EPL query./*w w  w  .  ja va  2  s.c om*/
 *
 * @param query    EPL query.
 * @param registry Registry to use.
 */
public void setEPL(String query, Registry registry) {
    if (registryKey == null) {
        eplStatement = query;
        synchronized (statementLock) {
            statement = provider.getEPAdministrator().createEPL(eplStatement);
            queryActivityMonitor.notify(eplStatement);
        }
        if (listener != null)
            addListener(listener);
    } else if (registry == null) {
        log.error("Cannot lookup Registry");
    } else {
        // You can't fetch while updating. And if you try to do so
        // you may end up getting an incorrect result. Also, changes
        // to registryKey during the process is not allowed.
        synchronized (registryFetchLock) {
            OMNode eplNode = registry.lookup(registryKey);
            OMNode eplNodeNew = null;
            if (eplNode == null) {
                log.error("Registry lookup for EPL statement failed");
            } else if (eplNode instanceof OMElement) {
                ((OMElement) eplNode).getAttribute(new QName("value")).setAttributeValue(eplStatement);
                eplNodeNew = eplNode;
            } else if (eplNode instanceof OMText) {
                DataHandler dh = (DataHandler) (((OMText) eplNode).getDataHandler());
                if (dh == null) {
                    log.error("Error getting EPL statement");
                } else {
                    DataHandler dhNew = null;
                    try {
                        Object content = dh.getContent();
                        if (content instanceof InputStream) {
                            dhNew = new DataHandler(new ByteArrayInputStream(eplStatement.getBytes("UTF-8")),
                                    dh.getContentType());
                        } else if (content instanceof String)
                            dhNew = new DataHandler(eplStatement, dh.getContentType());
                        else {
                            log.error("Content fetched from Registry is not valid");
                        }
                        if (dhNew != null) {
                            OMFactory omFactory = OMAbstractFactory.getOMFactory();
                            eplNodeNew = omFactory.createOMText(dhNew, false);
                        } else {
                            log.error("Failed Creating Data Handler");
                        }
                    } catch (IOException e) {
                        log.error("An error occured while changing EPL statement " + e.getMessage());
                    }
                }
            } else
                log.error("Invalid EPL statement object retrieved");
            if (eplNodeNew == null) {
                log.error("An error occured while changing EPL statement");
            } else {
                updateRegistryResource(registryKey, eplNodeNew, registry);
                synchronized (expiryTimeLock) {
                    expiryTime = 0L;
                }
            }
        }
    }
    log.info("EPL Statement successfully changed");
}

From source file:org.sciflex.plugins.synapse.esper.mediators.helpers.EPLStatementHelper.java

/**
 * Invokes EPL Statement Helper before mediating the current message.
 * @param mc Message Context of the current message.
 *///from  w  w  w  .  j  a va 2  s  .  com
public void invoke(MessageContext mc) {
    if (statement != null && !updateRequired()) {
        queryActivityMonitor.incrementCount();
        return;
    }
    if (registryKey == null)
        log.error("EPL statement has not been set");
    else {
        Registry registry = null;
        OMNode eplNode = null;
        RegistryEntry re = null;
        long cachableDuration = 0;
        // Lock Registry key during the fetch.
        synchronized (registryFetchLock) {
            registry = mc.getConfiguration().getRegistry();
            eplNode = registry.lookup(registryKey);
            try {
                re = registry.getRegistryEntry(registryKey);
                cachableDuration = re.getCachableDuration();
            } catch (Throwable e) {
                // FIXME: ESB 1.7.x and Synapse 1.2+ incompatibility can lead to errors, such as
                // java.lang.NoSuchMethodError which is caught in this block. Hence the use
                // of Throwable. This should be fixed once we move to ESB 2.0 series.
                log.error("An error occured while fetching EPL statement Registry Entry Details "
                        + e.getMessage());
            }
        }
        if (eplNode == null) {
            log.error("Registry lookup for EPL statement failed");
            return;
        }
        if (eplNode instanceof OMElement) {
            eplStatement = ((OMElement) eplNode).getAttributeValue(new QName("value"));
            if (eplStatement == null) {
                log.error("Error getting EPL statement");
                return;
            }
            try {
                synchronized (statementLock) {
                    statement = provider.getEPAdministrator().createEPL(eplStatement);
                    queryActivityMonitor.notify(eplStatement);
                }
                if (listener != null)
                    addListener(listener);
                log.info("EPStatement created");
            } catch (Exception e) {
                log.error("An error occured while setting EPL statement " + e.getMessage());
            }
        } else if (eplNode instanceof OMText) {
            DataHandler dh = (DataHandler) (((OMText) eplNode).getDataHandler());
            if (dh == null) {
                log.error("Error getting EPL statement");
                return;
            }
            try {
                Object content = dh.getContent();
                if (content instanceof InputStream) {
                    BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content));
                    StringBuffer sb = new StringBuffer();
                    String str;
                    while ((str = br.readLine()) != null) {
                        sb.append(" ");
                        sb.append(str);
                    }
                    br.close();
                    eplStatement = sb.toString();
                } else if (content instanceof String)
                    eplStatement = (String) content;
                else {
                    log.error("Content fetched from Registry is not valid");
                }
                if (eplStatement != null)
                    log.info("Got EPL Statement from Registry");
                else {
                    log.error("Invalid EPL statement");
                    return;
                }
            } catch (IOException e) {
                log.error("An error occured while reading EPL statement " + e.getMessage());
                return;
            }
            try {
                synchronized (statementLock) {
                    statement = provider.getEPAdministrator().createEPL(eplStatement);
                    queryActivityMonitor.notify(eplStatement);
                }
                if (listener != null)
                    addListener(listener);
                log.info("EPStatement created");
            } catch (Exception e) {
                log.error("An error occured while setting EPL statement " + e.getMessage());
            }
        } else {
            log.error("Invalid EPL statement object retrieved");
            return;
        }
        queryActivityMonitor.incrementCount();
        Date now = new Date();
        if (cachableDuration != 0) {
            synchronized (expiryTimeLock) {
                expiryTime = cachableDuration + now.getTime();
            }
            log.info("Cached EPL statement expires in " + cachableDuration + "ms");
        } else {
            synchronized (expiryTimeLock) {
                expiryTime = now.getTime();
            }
            log.info("Cached EPL statement expires in 0ms");
        }
    }
}

From source file:org.wso2.appserver.integration.resources.resource.test.NonXMLResourceAddTestCase.java

@Test(groups = { "wso2.as" })
public void testAddNoneXmlResource()
        throws ResourceAdminServiceExceptionException, IOException, XPathExpressionException {

    //add a collection to the registry
    String collectionPath = resourceAdminServiceClient.addCollection(PARENT_PATH, RES_FILE_FOLDER, "",
            "contains Text Res Files");
    String authorUserName = resourceAdminServiceClient.getResource((PARENT_PATH + RES_FILE_FOLDER))[0]
            .getAuthorUserName();/*from  w  w w .ja  va  2  s .c om*/
    assertTrue(asServer.getContextTenant().getContextUser().getUserName().equalsIgnoreCase(authorUserName),
            PARENT_PATH + RES_FILE_FOLDER + " creation failure");
    log.info("collection added to " + collectionPath);

    // Changing media type
    collectionPath = resourceAdminServiceClient.addCollection(PARENT_PATH, RES_FILE_FOLDER,
            "application/vnd.wso2.esb", "application/vnd.wso2.esb media type collection");
    authorUserName = resourceAdminServiceClient.getResource((PARENT_PATH + RES_FILE_FOLDER))[0]
            .getAuthorUserName();
    assertTrue(asServer.getContextTenant().getContextUser().getUserName().equalsIgnoreCase(authorUserName),
            PARENT_PATH + RES_FILE_FOLDER + " updating failure");
    log.info("collection updated in " + collectionPath);

    String resource = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "AS"
            + File.separator + "txt" + File.separator + "sampleText.txt";

    DataHandler dh = new DataHandler(new URL("file:///" + resource));

    resourceAdminServiceClient.addResource(PARENT_PATH + RES_FILE_FOLDER + "/" + TEXT_FILE_NAME, "text/html",
            "txtDesc", dh);

    String textContent = resourceAdminServiceClient
            .getTextContent(PARENT_PATH + RES_FILE_FOLDER + "/" + TEXT_FILE_NAME);

    assertTrue(dh.getContent().toString().equalsIgnoreCase(textContent),
            "Text file has not been added properly ");
}

From source file:org.wso2.appserver.integration.resources.resource.test.RegistryResourceTestCase.java

@Test(groups = { "wso2.as" }, dependsOnMethods = "testCreateCollection")
public void testAddResourceFromLocalFile() throws IOException, ResourceAdminServiceExceptionException {

    String RESOURCE_NAME = "sampleText.txt";
    String resource = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "AS"
            + File.separator + "txt" + File.separator + RESOURCE_NAME;

    DataHandler dh = new DataHandler(new URL("file:///" + resource));

    resourceAdminServiceClient.addResource(PARENT_PATH + "/" + WSO2_COLL + "/" + RESOURCE_NAME, "text/html",
            "txtDesc", dh);
    String textContent = resourceAdminServiceClient
            .getTextContent(PARENT_PATH + "/" + WSO2_COLL + "/" + RESOURCE_NAME);

    assertTrue(dh.getContent().toString().equalsIgnoreCase(textContent), "Added resource not found");
    log.info("Resource successfully added to the registry and retrieved contents successfully");

}