Example usage for java.lang NullPointerException getMessage

List of usage examples for java.lang NullPointerException getMessage

Introduction

In this page you can find the example usage for java.lang NullPointerException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.computeforcancer.android.client.Monitor.java

/**
 * Reads client status via RPCs/*from w w w. j a va2s  . c om*/
 * Optimized to retrieve only subset of information (required to determine wakelock state) if screen is turned off
 * @param forceCompleteUpdate forces update of entire status information, regardless of screen status
 */
private synchronized void readClientStatus(Boolean forceCompleteUpdate) {
    try {
        CcStatus status; // read independently of screen status

        // complete status read, depending on screen status
        // screen off: only read computing status to adjust wakelock, do not send broadcast
        // screen on: read complete status, set ClientStatus, send broadcast
        // forceCompleteUpdate: read complete status, independently of screen setting
        if (screenOn || forceCompleteUpdate) {
            // complete status read, with broadcast
            if (Logging.VERBOSE)
                Log.d(Logging.TAG, "readClientStatus(): screen on, get complete status");
            status = clientInterface.getCcStatus();
            CcState state = clientInterface.getState();
            ArrayList<Transfer> transfers = clientInterface.getFileTransfers();
            AcctMgrInfo acctMgrInfo = clientInterface.getAcctMgrInfo();
            ArrayList<Notice> newNotices = clientInterface
                    .getNotices(Monitor.getClientStatus().getMostRecentNoticeSeqNo());

            if ((status != null) && (state != null) && (state.results != null) && (state.projects != null)
                    && (transfers != null) && (state.host_info != null) && (acctMgrInfo != null)) {
                Monitor.getClientStatus().setClientStatus(status, state.results, state.projects, transfers,
                        state.host_info, acctMgrInfo, newNotices);
            } else {
                String nullValues = "";
                try {
                    if (state == null)
                        nullValues += "state,";
                    if (state.results == null)
                        nullValues += "state.results,";
                    if (state.projects == null)
                        nullValues += "state.projects,";
                    if (transfers == null)
                        nullValues += "transfers,";
                    if (state.host_info == null)
                        nullValues += "state.host_info,";
                    if (acctMgrInfo == null)
                        nullValues += "acctMgrInfo,";
                } catch (NullPointerException e) {
                }
                ;
                if (Logging.ERROR)
                    Log.e(Logging.TAG, "readClientStatus(): connection problem, null: " + nullValues);
            }

            // update notices notification
            //NoticeNotification.getInstance(getApplicationContext()).update(Monitor.getClientStatus().getRssNotices(), Monitor.getAppPrefs().getShowNotificationForNotices());

            // check whether monitor is still intended to update, if not, skip broadcast and exit...
            if (updateBroadcastEnabled) {
                Intent clientStatus = new Intent();
                clientStatus.setAction("org.computeforcancer.android.clientstatus");
                getApplicationContext().sendBroadcast(clientStatus);
            }
        } else {
            // read only ccStatus to adjust wakelocks and service state independently of screen status
            status = clientInterface.getCcStatus();
        }

        // independent of screen on off:
        // wake locks and foreground enabled when Client is not suspended, therefore also during
        // idle.
        // treat cpu throttling as if it was computing.
        Boolean computing = (status.task_suspend_reason == BOINCDefs.SUSPEND_NOT_SUSPENDED)
                || (status.task_suspend_reason == BOINCDefs.SUSPEND_REASON_CPU_THROTTLE);
        if (Logging.VERBOSE)
            Log.d(Logging.TAG, "readClientStatus(): computation enabled: " + computing);
        Monitor.getClientStatus().setWifiLock(computing);
        Monitor.getClientStatus().setWakeLock(computing);
        SharedPreferences mSharedPreferences = getApplicationContext().getSharedPreferences(
                "org.computeforcancer.android", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
        //Log.d("TEST", "deviceStatus.getStatus().user_active " + deviceStatus.getStatus().user_active);
        if (computing && !deviceStatus.getStatus().user_active) {
            //Log.d("TEST", "computing");
            currTime = System.currentTimeMillis();
            if (currTime - prevTime < 14000) {
                temp = mSharedPreferences.getLong(
                        SharedPrefs.DONATION_TIME + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""),
                        0);
                ;
                //Log.d("TEST", "1get DONATION_TIME " + temp);
                //Log.d("TEST", "1put DONATION_TIME " + (temp +
                //      currTime - prevTime));
                mSharedPreferences.edit()
                        .putLong(
                                SharedPrefs.DONATION_TIME
                                        + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""),
                                temp + currTime - prevTime)
                        .commit();
            }
            prevTime = currTime;
            //Log.d("TEST", "1get START_SESSION_TIME " + startSessionTime);
            if (startSessionTime == 0) {
                //Log.d("TEST", "1put START_SESSION_TIME " + currTime);
                startSessionTime = currTime;
            }
        } else {
            //Log.d("TEST", "2get START_SESSION_TIME " + startSessionTime);
            if (startSessionTime != 0) {
                currTime = System.currentTimeMillis();
                mSharedPreferences.edit()
                        .putLong(
                                SharedPrefs.LAST_SESSION_TIME
                                        + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""),
                                currTime - startSessionTime)
                        .commit();

                //Log.d("TEST", "2get DONATION_TIME " + mSharedPreferences.getLong(SharedPrefs.DONATION_TIME + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""), 0));

                temp = mSharedPreferences.getLong(
                        SharedPrefs.DONATION_TIME + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""),
                        0);
                ;
                mSharedPreferences.edit()
                        .putLong(
                                SharedPrefs.DONATION_TIME
                                        + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""),
                                temp + currTime - prevTime)
                        .commit();
                prevTime = currTime;

                sendDonationTimeMessage(
                        mSharedPreferences.getLong(SharedPrefs.LAST_SESSION_TIME
                                + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""), 0),
                        mSharedPreferences.getLong(SharedPrefs.DONATION_TIME
                                + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""), 0),
                        mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""));
                //Log.d("TEST", "2put START_SESSION_TIME " + 0);
                startSessionTime = 0;
                //Log.d("TEST", "System.currentTimeMillis() " + System.currentTimeMillis());
                //Log.d("TEST", "System.getLastNotification() " + mSharedPreferences.getLong(SharedPrefs.LAST_NOTIFICATION, 0));
                //Log.d("TEST", "System.getNotificationDelay() " + mSharedPreferences.getLong(SharedPrefs.NOTIFICATION_DELAY, Long.MAX_VALUE));
                if (currTime - mSharedPreferences.getLong(SharedPrefs.LAST_NOTIFICATION, 0) > mSharedPreferences
                        .getLong(SharedPrefs.NOTIFICATION_DELAY, Long.MAX_VALUE)) {
                    mSharedPreferences.edit().putLong(SharedPrefs.LAST_NOTIFICATION, System.currentTimeMillis())
                            .commit();
                    //Log.d("TEST", "get DONATION_TIME " + mSharedPreferences.getLong(SharedPrefs.DONATION_TIME + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""), 0));
                    sendNotification(mSharedPreferences.getLong(SharedPrefs.DONATION_TIME
                            + mSharedPreferences.getString(SharedPrefs.CURRENT_EMAIL, ""), 0));
                }
            }
        }
        //ClientNotification.getInstance(getApplicationContext()).update(Monitor.getClientStatus(), this, computing);

    } catch (Exception e) {
        if (Logging.ERROR)
            Log.e(Logging.TAG, "Monitor.readClientStatus excpetion: " + e.getMessage(), e);
    }
}

From source file:org.openmrs.module.rheapocadapter.impl.HL7MessageTransformer.java

public ORU_R01 generateORU_R01Message(Patient pat, List<Encounter> encounterList) throws HL7Exception {
    MSH msh = r01.getMSH();/*from w w  w .j a v a2s  .  co m*/
    String implementationId = "";
    String fosaid = "";
    // Get current date
    String dateFormat = "yyyyMMddHHmmss";
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    String formattedDate = formatter.format(new Date());

    msh.getFieldSeparator().setValue(RHEAHL7Constants.FIELD_SEPARATOR);//
    msh.getEncodingCharacters().setValue(RHEAHL7Constants.ENCODING_CHARACTERS);//
    msh.getVersionID().getInternationalizationCode().getIdentifier()
            .setValue(RHEAHL7Constants.INTERNATIONALIZATION_CODE);//
    msh.getVersionID().getVersionID().setValue(RHEAHL7Constants.VERSION);//
    msh.getDateTimeOfMessage().getTime().setValue(formattedDate);//
    try {
        implementationId = (Context.getAdministrationService().getImplementationId()
                .getImplementationId() != null)
                        ? Context.getAdministrationService().getImplementationId().getImplementationId()
                        : "rwanda000";
    } catch (NullPointerException e) {
        log.error("No Implementation Id  set;");
        implementationId = "rwanda000";
    }
    implementationId = implementationId.toLowerCase();
    fosaid = implementationId.substring(implementationId.indexOf("rwanda") + 6);
    msh.getSendingFacility().getNamespaceID().setValue(fosaid);//
    msh.getMessageType().getMessageCode().setValue(RHEAHL7Constants.MESSAGE_TYPE);//
    msh.getMessageType().getTriggerEvent().setValue(RHEAHL7Constants.TRIGGER_EVENT);//
    msh.getMessageType().getMessageStructure().setValue(RHEAHL7Constants.MESSAGE_STRUCTURE);//
    msh.getReceivingFacility().getNamespaceID().setValue(RHEAHL7Constants.RECEIVING_FACILITY);//
    msh.getProcessingID().getProcessingID().setValue(RHEAHL7Constants.PROCESSING_ID);//
    msh.getProcessingID().getProcessingMode().setValue(RHEAHL7Constants.PROCESSING_MODE);//
    msh.getMessageControlID().setValue(UUID.randomUUID().toString());//

    msh.getAcceptAcknowledgmentType().setValue(RHEAHL7Constants.ACK_TYPE);
    msh.getApplicationAcknowledgmentType().setValue(RHEAHL7Constants.APPLICATION_ACK_TYPE);
    msh.getMessageProfileIdentifier(0).getEntityIdentifier().setValue(RHEAHL7Constants.MSG_PROFILE_IDENTIFIER);
    PID pid = r01.getPATIENT_RESULT().getPATIENT().getPID();

    Patient patient = pat;
    int i = 0;
    String id = "";
    String idType = "";
    try {
        {
            PatientIdentifierType nid = Context.getPatientService().getPatientIdentifierTypeByName("NID");
            PatientIdentifierType mutuelle = Context.getPatientService()
                    .getPatientIdentifierTypeByName("Mutuelle");
            PatientIdentifierType rama = Context.getPatientService().getPatientIdentifierTypeByName("RAMA");
            PatientIdentifierType primaryCare = Context.getPatientService()
                    .getPatientIdentifierTypeByName("Primary Care ID Type");

            if (getPatientIdentifierByIdentifierType(patient, nid) != null) {
                log.info("Get NID");
                id = "";
                idType = "";
                idType = nid.getName();
                id = getPatientIdentifierByIdentifierType(patient, nid).getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (getPatientIdentifierByIdentifierType(patient, rama) != null) {
                log.info("Get Rama");
                id = "";
                idType = "";
                idType = rama.getName();
                id = getPatientIdentifierByIdentifierType(patient, rama).getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (getPatientIdentifierByIdentifierType(patient, mutuelle) != null) {
                log.info("Get Mutuelle");
                id = "";
                idType = "";
                idType = mutuelle.getName();
                id = getPatientIdentifierByIdentifierType(patient, mutuelle).getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (getPatientIdentifierByIdentifierType(patient, primaryCare) != null) {
                log.info("Get OMRS");
                id = "";
                idType = "";
                try {
                    implementationId = (Context.getAdministrationService().getImplementationId()
                            .getImplementationId() != null)
                                    ? Context.getAdministrationService().getImplementationId()
                                            .getImplementationId()
                                    : "rwanda000";
                } catch (NullPointerException e) {
                    log.error("No Implementation Id  set;");
                    implementationId = "rwanda000";
                }
                implementationId = implementationId.toLowerCase();
                fosaid = implementationId.substring(implementationId.indexOf("rwanda") + 6);
                idType = "OMRS" + fosaid;
                id = getPatientIdentifierByIdentifierType(patient, primaryCare).getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (!patient.getPatientIdentifier().getIdentifierType().equals(nid)
                    && !patient.getPatientIdentifier().getIdentifierType().equals(rama)
                    && !patient.getPatientIdentifier().getIdentifierType().equals(mutuelle)
                    && !patient.getPatientIdentifier().getIdentifierType().equals(primaryCare)) {
                id = "";
                idType = "";
                log.info("Get " + patient.getPatientIdentifier().getIdentifier());
                idType = patient.getPatientIdentifier().getIdentifierType().getName();
                id = patient.getPatientIdentifier().getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }

            }

        }
    } catch (Exception e) {
        log.info(e.getMessage());
        idType = patient.getPatientIdentifier().getIdentifierType().getName();
        id = patient.getPatientIdentifier().getIdentifier();

        pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
        pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);

    }

    // Cohort singlePatientCohort = new Cohort();
    // singlePatientCohort.addMember(pat.getId());
    //
    // Map<Integer, PatientIdentifier> patientIdentifierMap = Context
    // .getPatientSetService().getPatientIdentifiersByType(
    // singlePatientCohort,
    // Context.getPatientService()
    // .getPatientIdentifierTypeByName(
    // RHEAHL7Constants.IDENTIFIER_TYPE));
    //
    // PID pid = r01.getPATIENT_RESULT().getPATIENT().getPID();
    //
    // pid.getSetIDPID().setValue(RHEAHL7Constants.IDPID);
    // pid.getPatientIdentifierList(0)
    // .getIDNumber()
    // .setValue(
    // patientIdentifierMap
    // .get(patientIdentifierMap.keySet().iterator()
    // .next()).getIdentifier());
    //
    // pid.getPatientIdentifierList(0).getIdentifierTypeCode()
    // .setValue(RHEAHL7Constants.IDENTIFIER_TYPE);
    pid.getPatientName(0).getFamilyName().getSurname().setValue(pat.getFamilyName());
    pid.getPatientName(0).getGivenName().setValue(pat.getGivenName());

    PV1 pv1 = r01.getPATIENT_RESULT().getPATIENT().getVISIT().getPV1();

    pv1.getPatientClass().setValue(RHEAHL7Constants.PATIENT_CLASS);
    pv1.getAssignedPatientLocation().getFacility().getNamespaceID()
            .setValue(encounterList.get(0).getLocation().getName());
    pv1.getAssignedPatientLocation().getPointOfCare()
            .setValue(encounterList.get(0).getLocation().getLocationId().toString());
    pv1.getAdmissionType().setValue(encounterList.get(0).getEncounterType().getName());

    pv1.getPatientClass().setValue(RHEAHL7Constants.PATIENT_CLASS);
    pv1.getAssignedPatientLocation().getFacility().getNamespaceID()
            .setValue(encounterList.get(0).getLocation().getName());
    pv1.getAssignedPatientLocation().getPointOfCare()
            .setValue(encounterList.get(0).getLocation().getLocationId().toString());
    pv1.getAdmissionType().setValue(encounterList.get(0).getEncounterType().getName());

    Person provider = encounterList.get(0).getProvider();
    TransactionService service = Context.getService(TransactionService.class);
    // Cohort singleProviderCohort = new Cohort();
    // singleProviderCohort.addMember(provider.getId());
    //
    // Map<Integer, PatientIdentifier> providerIdentifierMap = Context
    // .getPatientSetService().getPatientIdentifiersByType(
    // singleProviderCohort,
    // Context.getPatientService()
    // .getPatientIdentifierTypeByName("NID"));
    //
    // String providerNID = providerIdentifierMap.get(
    // providerIdentifierMap.keySet().iterator().next())
    // .getIdentifier();
    String providerNID = service.getPersonAttributesByPerson(provider, "NID");
    log.info(providerNID + " Provider NID");

    pv1.getAttendingDoctor(0).getFamilyName().getSurname()
            .setValue(encounterList.get(0).getProvider().getFamilyName());
    pv1.getAttendingDoctor(0).getGivenName().setValue(encounterList.get(0).getProvider().getGivenName());
    pv1.getAttendingDoctor(0).getIdentifierTypeCode().setValue("NID");
    pv1.getAttendingDoctor(0).getIDNumber().setValue(providerNID);
    pv1.getAdmitDateTime().getTime()
            .setValue(new SimpleDateFormat("yyyyMMddhhmm").format(encounterList.get(0).getDateCreated()));

    // populate ORC segments

    try {
        createORC(r01, encounterList);
    } catch (Exception e) {
        log.error("Error generated", e);
    }

    // populate OBR segments

    try {
        createOBREnc(r01, encounterList);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error("Error generated", e);
    }

    // populate OBX segments

    ConceptService cs = Context.getConceptService();

    int counter = 1;

    return r01;
}

From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java

public ImageHolder getImageHolder(Map<String, String[]> params)
        throws URISyntaxException, IOException, ImageManagerException {

    /*/*from  w ww .  j  ava2  s .  c om*/
     * -------------------------------- get central configuration --------------------------------
     */
    URI sourceImageUrl = null;
    ContentServerConfiguration config = ContentServerConfiguration.getInstance();
    if (!params.get("sourcepath")[0].startsWith("file:") && !params.get("sourcepath")[0].startsWith("http:")) {
        String path = params.get("sourcepath")[0].replace(" ", "+");
        sourceImageUrl = new URI(config.getRepositoryPathImages() + path);
    } else {
        String path = params.get("sourcepath")[0].replace(" ", "+");
        sourceImageUrl = new URI(path);
    }

    try {
        Cache cc = null;
        // ServletOutputStream output = response.getOutputStream();
        if (params.get("thumbnail") != null) {
            cc = ContentServer.getThumbnailCache();
        } else {
            cc = ContentServer.getContentCache();
        }
        String myUniqueID = getContentCacheIdForParamMap(params, config);
        LOGGER.trace("myUniqueId: " + myUniqueID);
        String targetExtension = params.get("format")[0];

        boolean ignoreCache = false;
        /* check if cache should be ignored */
        if (params.get("ignoreCache") != null) {
            String ignore = params.get("ignoreCache")[0].trim();
            ignoreCache = Boolean.parseBoolean(ignore);
        }
        boolean useCache = false;
        if (params.get("thumbnail") != null) {
            useCache = config.getThumbnailCacheUse();
        } else {
            useCache = config.getContentCacheUse();
        }

        if (params.get("highlight") != null) {
            useCache = false;
        }
        if (cc == null || !useCache || params.get("highlight") != null) {
            ignoreCache = true;
            cc = null;
            LOGGER.debug("cache deactivated via configuration");
        }

        // Image found in cache
        if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) {
            LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension);
            try {
                CacheObject co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getValue();
                return new ImageHolder(co.getData());

            } catch (NullPointerException e) {
                LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension);
            }
            // if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) {
            // LOGGER.debug("get file from cache: " + myUniqueID);
            //
            // RenderedImage ri = (RenderedImage) cc.get(myUniqueID + "." + targetExtension).getObjectValue();
            // JpegInterpreter ii = new JpegInterpreter(ri);
            // ii.writeToStream(null, baos);
            // return baos.toByteArray();
        } else if (!ignoreCache) {
            LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension);
        }

        /*
         * -------------------------------- retrieve source image from url --------------------------------
         */
        ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL());
        LOGGER.trace("imageManager initialized");

        /*
         * -------------------------------- set the defaults --------------------------------
         */
        int angle = 0;
        int scaleX = 100;
        int scaleY = 100;
        int scaleType = ImageManager.SCALE_BY_PERCENT;
        LinkedList<String> highlightCoordinateList = null;
        Color highlightColor = null;
        Watermark myWatermark = null;
        LOGGER.trace("Variables set");

        /*
         * -------------------------------- rotate --------------------------------
         */
        if (params.get("rotate") != null) {
            angle = Integer.parseInt(params.get("rotate")[0]);
            LOGGER.trace("rotate image:" + angle);
        }

        /*
         * -------------------------------- scale: scale the image to some percent value --------------------------------
         */
        if (params.get("scale") != null) {
            scaleX = Integer.parseInt(params.get("scale")[0]);
            scaleY = scaleX;
            scaleType = ImageManager.SCALE_BY_PERCENT;
            LOGGER.trace("scale image to percent:" + scaleX);
        }

        if (params.get("width") != null && params.get("height") != null) {
            scaleX = Integer.parseInt(params.get("width")[0]);
            scaleY = Integer.parseInt(params.get("height")[0]);
            scaleType = ImageManager.SCALE_TO_BOX;
        }

        /*
         * -------------------------------- width: scale image to fixed width --------------------------------
         */
        else if (params.get("width") != null) {
            scaleX = Integer.parseInt(params.get("width")[0]);
            scaleY = 0;
            scaleType = ImageManager.SCALE_BY_WIDTH;
            LOGGER.trace("scale image to width:" + scaleX);
        }

        /*
         * -------------------------------- height: scale image to fixed height --------------------------------
         */
        else if (params.get("height") != null) {
            scaleY = Integer.parseInt(params.get("height")[0]);
            scaleX = 0;
            scaleType = ImageManager.SCALE_BY_HEIGHT;
            LOGGER.trace("scale image to height:" + scaleY);
        }

        /*
         * -------------------------------- highlight --------------------------------
         */
        if (params.get("highlight") != null) {
            highlightCoordinateList = new LinkedList<String>();
            String highlight = params.get("highlight")[0];
            StrTokenizer areas = new StrTokenizer(highlight, "$");
            for (String area : areas.getTokenArray()) {
                StrTokenizer coordinates = new StrTokenizer(area, ",");
                highlightCoordinateList.add(coordinates.getContent());
            }
            highlightColor = config.getDefaultHighlightColor();
        }

        /*
         * -------------------------------- insert watermark, if it should be used --------------------------------
         */
        if (params.get("ignoreWatermark") == null) {
            if (config.getWatermarkUse()) {
                File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath()));
                myWatermark = Watermark.generateWatermark(params, watermarkfile);
            }
        }

        /*
         * -------------------------------- prepare target --------------------------------
         */
        // change to true if watermark should scale
        boolean scaleWatermark = false;
        if (config.getScaleWatermark()) {
            scaleWatermark = true;
        }
        RenderedImage targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle,
                highlightCoordinateList, highlightColor, myWatermark, scaleWatermark, ImageManager.BOTTOM);
        LOGGER.trace("Creating ImageInterpreter");
        ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension);
        ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file
        LOGGER.trace("Image stored in " + wi.getClass().getCanonicalName());

        /*
         * -------------------------------- set file name and attachment header from parameter or from configuration
         * --------------------------------
         */
        // StringBuilder targetFileName = new StringBuilder();
        // if (config.getSendImageAsAttachment()) {
        // targetFileName.append("attachment; ");
        // }
        // targetFileName.append("filename=");
        //
        // if (params.get("targetFileName") != null) {
        // targetFileName.append(params.get("targetFileName"));
        // } else {
        // String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(), "." +
        // targetFormat.getFileExtension());
        // targetFileName.append(filename);
        // }

        /*
         * -------------------------------- resolution --------------------------------
         */
        LOGGER.trace("Setting image resolution");
        if (params.get("resolution") != null) {
            wi.setXResolution(Float.parseFloat(params.get("resolution")[0]));
            wi.setYResolution(Float.parseFloat(params.get("resolution")[0])); // TODO Is this correct?
        } else {
            wi.setXResolution(config.getDefaultResolution());
            wi.setYResolution(config.getDefaultResolution());
        }
        LOGGER.trace("Finished setting image resolution");
        /*
         * -------------------------------- write target image to stream --------------------------------
         */

        byte[] data = wi.writeToStreamAndByteArray(new ByteArrayOutputStream());
        ImageHolder returnImage = new ImageHolder(data, wi.getWidth(), wi.getHeight());
        if (cc != null && highlightColor == null) {
            cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data)));
        }
        LOGGER.trace("Done writing image to stream");
        return returnImage;
    } catch (CacheException e) {
        LOGGER.error("CacheException", e);
    } catch (MalformedURLException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (ImageManipulatorException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (WatermarkException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return null;
}

From source file:org.kontalk.xmppserver.KontalkIqRegister.java

@Override
public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
        Queue<Packet> results, Map<String, Object> settings) throws XMPPException {
    if (log.isLoggable(Level.FINEST)) {
        log.finest("Processing packet: " + packet.toString());
    }/*ww w .  j  av a 2 s. co m*/
    if (session == null) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Session is null, ignoring");
        }

        return;
    }

    BareJID id = session.getDomainAsJID().getBareJID();

    if (packet.getStanzaTo() != null) {
        id = packet.getStanzaTo().getBareJID();
    }
    try {

        if ((packet.getPacketFrom() != null) && packet.getPacketFrom().equals(session.getConnectionId())
                && (!session.isAuthorized()
                        || (session.isUserId(id) || session.isLocalDomain(id.toString(), false)))) {

            Element request = packet.getElement();

            if (!session.isAuthorized()) {
                if (!session.getDomain().isRegisterEnabled()) {
                    results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet,
                            "Registration is not allowed for this domain.", true));
                    ++statsInvalidRegistrations;
                    return;
                }
            }

            StanzaType type = packet.getType();

            switch (type) {
            case set: {
                // FIXME handle all the cases according to the FORM_TYPE

                Element query = request.getChild(Iq.QUERY_NAME, XMLNSS[0]);
                Element formElement = (query != null) ? query.getChild(IQ_FORM_ELEM_NAME, IQ_FORM_XMLNS) : null;
                if (formElement != null) {
                    Form form = new Form(formElement);

                    // phone number: verification code
                    String phone = form.getAsString(FORM_FIELD_PHONE);
                    if (!session.isAuthorized() && phone != null) {
                        boolean force;
                        try {
                            force = form.getAsBoolean(FORM_FIELD_FORCE);
                        } catch (NullPointerException e) {
                            force = false;
                        }
                        boolean fallback;
                        try {
                            fallback = form.getAsBoolean(FORM_FIELD_FALLBACK);
                        } catch (NullPointerException e) {
                            fallback = false;
                        }
                        String challenge;
                        try {
                            challenge = form.getAsString(FORM_FIELD_CHALLENGE);
                        } catch (NullPointerException e) {
                            challenge = null;
                        }

                        Packet response = registerPhone(session, packet, phone, force, fallback, challenge,
                                results);
                        statsRegistrationAttempts++;
                        packet.processedBy(ID);
                        if (response != null)
                            results.offer(response);
                        break;
                    }

                    // verification code: key submission
                    String code = form.getAsString(FORM_FIELD_CODE);
                    // get public key block from client certificate
                    byte[] publicKeyData = getPublicKey(session);

                    if (!session.isAuthorized()) {

                        // load public key
                        PGPPublicKey key = loadPublicKey(publicKeyData);
                        // verify user id
                        BareJID jid = verifyPublicKey(session, key);

                        if (verifyCode(session, jid, code)) {
                            byte[] signedKey = signPublicKey(session, publicKeyData);

                            Packet response = register(session, packet, jid, key.getFingerprint(), signedKey);
                            statsRegisteredUsers++;
                            packet.processedBy(ID);
                            results.offer(response);
                        } else {
                            // invalid verification code
                            results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
                                    ERROR_INVALID_CODE, true));
                        }

                        // clear throttling
                        clearThrottling(jid, session.getConnectionId());

                        break;
                    }

                    if (session.isAuthorized()) {
                        // private key storage
                        String privateKey = form.getAsString(FORM_FIELD_PRIVATEKEY);
                        if (privateKey != null) {
                            Packet response = storePrivateKey(session, repo, packet, privateKey);
                            packet.processedBy(ID);
                            results.offer(response);
                            break;
                        } else {
                            // public key + revoked key: key rollover or upgrade from legacy
                            String oldFingerprint;
                            try {
                                oldFingerprint = KontalkAuth.getUserFingerprint(session);
                            } catch (UserNotFoundException e) {
                                oldFingerprint = null;
                                log.log(Level.INFO, "user not found: {0}", session);
                            }

                            if (oldFingerprint != null) {
                                // do not use public key from certificate
                                publicKeyData = null;

                                // user already has a key, check if revoked key fingerprint matches
                                String publicKey = form.getAsString(FORM_FIELD_PUBLICKEY);
                                String revoked = form.getAsString(FORM_FIELD_REVOKED);
                                if (publicKey != null && revoked != null) {
                                    publicKeyData = Base64.decode(publicKey);
                                    byte[] revokedData = Base64.decode(revoked);
                                    KontalkKeyring keyring = getKeyring(session);
                                    if (!keyring.revoked(revokedData, oldFingerprint)) {
                                        // invalid revocation key
                                        log.log(Level.INFO, "Invalid revocation key for user {0}",
                                                session.getBareJID());
                                        results.offer(Authorization.FORBIDDEN.getResponseMessage(packet,
                                                ERROR_INVALID_REVOKED, false));
                                        break;
                                    }
                                }
                            }

                            // user has no key or revocation key was fine, accept the new key
                            if (publicKeyData != null) {
                                rolloverContinue(session, publicKeyData, packet, results);
                                break;
                            }
                        }
                    }
                }

                // bad request
                results.offer(
                        Authorization.BAD_REQUEST.getResponseMessage(packet, ERROR_MALFORMED_REQUEST, true));
                break;
            }

            case get: {
                Element query = request.getChild(Iq.QUERY_NAME, XMLNSS[0]);
                Element account = query.getChild(IQ_ACCOUNT_ELEM_NAME, IQ_ACCOUNT_XMLNS);
                if (account != null) {
                    String token = account.getChildCData(new String[] { IQ_ACCOUNT_ELEM_NAME,
                            IQ_ACCOUNT_PRIVATEKEY_ELEM_NAME, IQ_ACCOUNT_TOKEN_ELEM_NAME });

                    if (StringUtils.isNotEmpty(token)) {
                        Packet response = retrievePrivateKey(session, repo, packet, token);
                        response.processedBy(ID);
                        results.offer(response);
                        break;
                    }
                }

                // instructions form
                results.offer(buildInstructionsForm(packet));
                break;
            }
            default:
                results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect",
                        true));

                break;
            }
        } else {
            if (session.isUserId(id)) {

                // It might be a registration request from transport for
                // example...
                Packet pack_res = packet.copyElementOnly();

                pack_res.setPacketTo(session.getConnectionId());
                results.offer(pack_res);
            } else {
                results.offer(packet.copyElementOnly());
            }
        }
    } catch (NotAuthorizedException e) {
        results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
                "You are not authorized to change registration settings.\n" + e.getMessage(), true));
    } catch (TigaseDBException e) {
        log.warning("Database problem: " + e);
        results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet,
                "Database access problem, please contact administrator.", true));
    }
    // generated from PGP
    catch (IOException e) {
        log.warning("Unknown error: " + e);
        results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet,
                "Internal PGP error. Please contact administrator.", true));
    } catch (PGPException e) {
        e.printStackTrace(System.err);
        log.warning("PGP problem: " + e);
        results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, ERROR_INVALID_PUBKEY, true));
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.EntityRetryController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;//ww  w  .j  av a2 s.  c o  m
    }

    VitroRequest vreq = new VitroRequest(request);
    String siteAdminUrl = vreq.getContextPath() + Controllers.SITE_ADMIN;

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    epo.setBeanClass(Individual.class);
    epo.setImplementationClass(IndividualImpl.class);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    LoginStatusBean loginBean = LoginStatusBean.getBean(request);
    WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory(loginBean.getUserURI());

    IndividualDao ewDao = myWebappDaoFactory.getIndividualDao();
    epo.setDataAccessObject(ewDao);
    VClassDao vcDao = myWebappDaoFactory.getVClassDao();
    VClassGroupDao cgDao = myWebappDaoFactory.getVClassGroupDao();
    DataPropertyDao dpDao = myWebappDaoFactory.getDataPropertyDao();

    Individual individualForEditing = null;
    if (epo.getUseRecycledBean()) {
        individualForEditing = (Individual) epo.getNewBean();
    } else {
        String uri = vreq.getParameter("uri");
        if (uri != null) {
            try {
                individualForEditing = (Individual) ewDao.getIndividualByURI(uri);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
        } else {
            individualForEditing = new IndividualImpl();
            if (vreq.getParameter("VClassURI") != null) {
                individualForEditing.setVClassURI(vreq.getParameter("VClassURI"));
            }
        }

        epo.setOriginalBean(individualForEditing);

        //make a simple mask for the entity's id
        Object[] simpleMaskPair = new Object[2];
        simpleMaskPair[0] = "URI";
        simpleMaskPair[1] = individualForEditing.getURI();
        epo.getSimpleMask().add(simpleMaskPair);

    }

    //set any validators

    LinkedList lnList = new LinkedList();
    lnList.add(new RequiredFieldValidator());
    epo.getValidatorMap().put("Name", lnList);

    //make a postinsert pageforwarder that will send us to a new entity's fetch screen
    epo.setPostInsertPageForwarder(new EntityInsertPageForwarder());
    epo.setPostDeletePageForwarder(new UrlForwarder(siteAdminUrl));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(ewDao.getClass().getDeclaredMethod("getIndividualByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("EntityRetryController could not find the entityByURI method in the dao");
    }

    epo.setIdFieldName("URI");
    epo.setIdFieldClass(String.class);

    HashMap hash = new HashMap();

    if (individualForEditing.getVClassURI() == null) {
        // we need to do a special thing here to make an option list with option groups for the classgroups.
        List classGroups = cgDao.getPublicGroupsWithVClasses(true, true, false); // order by displayRank, include uninstantiated classes, don't get the counts of individuals
        Iterator classGroupIt = classGroups.iterator();
        ListOrderedMap optGroupMap = new ListOrderedMap();
        while (classGroupIt.hasNext()) {
            VClassGroup group = (VClassGroup) classGroupIt.next();
            List classes = group.getVitroClassList();
            optGroupMap.put(group.getPublicName(), FormUtils.makeOptionListFromBeans(classes, "URI", "Name",
                    individualForEditing.getVClassURI(), null, false));
        }
        hash.put("VClassURI", optGroupMap);
    } else {
        VClass vClass = null;
        Option opt = null;
        try {
            vClass = vcDao.getVClassByURI(individualForEditing.getVClassURI());
        } catch (Exception e) {
        }
        if (vClass != null) {
            opt = new Option(vClass.getURI(), vClass.getName(), true);
        } else {
            opt = new Option(individualForEditing.getVClassURI(), individualForEditing.getVClassURI(), true);
        }
        List<Option> optList = new LinkedList<Option>();
        optList.add(opt);
        hash.put("VClassURI", optList);
    }

    hash.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(individualForEditing));
    hash.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(individualForEditing));
    hash.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(individualForEditing));

    FormObject foo = new FormObject();
    foo.setOptionLists(hash);

    ListOrderedMap dpMap = new ListOrderedMap();

    //make dynamic datatype property fields
    List<VClass> vclasses = individualForEditing.getVClasses(true);
    if (vclasses == null) {
        vclasses = new ArrayList<VClass>();
        if (individualForEditing.getVClassURI() != null) {
            try {
                VClass cls = vreq.getUnfilteredWebappDaoFactory().getVClassDao()
                        .getVClassByURI(individualForEditing.getVClassURI());
                if (cls != null) {
                    vclasses.add(cls);
                }
            } catch (Exception e) {
            }
        }
    }
    List<DataProperty> allApplicableDataprops = new ArrayList<DataProperty>();
    for (VClass cls : vclasses) {
        List<DataProperty> dataprops = dpDao.getDataPropertiesForVClass(cls.getURI());
        for (DataProperty dp : dataprops) {
            boolean notDuplicate = true;
            for (DataProperty existingDp : allApplicableDataprops) {
                if (existingDp.getURI().equals(dp.getURI())) {
                    notDuplicate = false;
                    break;
                }
            }
            if (notDuplicate) {
                allApplicableDataprops.add(dp);
            }
        }
    }
    Collections.sort(allApplicableDataprops);

    if (allApplicableDataprops != null) {
        Iterator<DataProperty> datapropsIt = allApplicableDataprops.iterator();

        while (datapropsIt.hasNext()) {
            DataProperty d = datapropsIt.next();
            if (!dpMap.containsKey(d.getURI())) {
                dpMap.put(d.getURI(), d);
            }

        }

        if (individualForEditing.getDataPropertyList() != null) {
            Iterator<DataProperty> existingDps = individualForEditing.getDataPropertyList().iterator();
            while (existingDps.hasNext()) {
                DataProperty existingDp = existingDps.next();
                // Since the edit form begins with a "name" field, which gets saved as the rdfs:label,
                // do not want to include the label as well. 
                if (!existingDp.getPublicName().equals("label")) {
                    dpMap.put(existingDp.getURI(), existingDp);
                }
            }
        }

        List<DynamicField> dynamicFields = new ArrayList();
        Iterator<String> dpHashIt = dpMap.orderedMapIterator();
        while (dpHashIt.hasNext()) {
            String uri = dpHashIt.next();
            DataProperty dp = (DataProperty) dpMap.get(uri);
            DynamicField dynamo = new DynamicField();
            dynamo.setName(dp.getPublicName());
            dynamo.setTable("DataPropertyStatement");
            dynamo.setVisible(dp.getDisplayLimit());
            dynamo.setDeleteable(true);
            DynamicFieldRow rowTemplate = new DynamicFieldRow();
            Map parameterMap = new HashMap();
            parameterMap.put("DatatypePropertyURI", dp.getURI());
            rowTemplate.setParameterMap(parameterMap);
            dynamo.setRowTemplate(rowTemplate);
            try {
                Iterator<DataPropertyStatement> existingValues = dp.getDataPropertyStatements().iterator();
                while (existingValues.hasNext()) {
                    DataPropertyStatement existingValue = existingValues.next();
                    DynamicFieldRow row = new DynamicFieldRow();
                    //TODO: UGH
                    //row.setId(existingValue.getId());
                    row.setParameterMap(parameterMap);
                    row.setValue(existingValue.getData());
                    if (dynamo.getRowList() == null)
                        dynamo.setRowList(new ArrayList());
                    dynamo.getRowList().add(row);
                }
            } catch (NullPointerException npe) {
                //whatever
            }
            if (dynamo.getRowList() == null)
                dynamo.setRowList(new ArrayList());
            dynamo.getRowList().add(rowTemplate);
            dynamicFields.add(dynamo);
        }
        foo.setDynamicFields(dynamicFields);
    }

    foo.setErrorMap(epo.getErrMsgMap());

    epo.setFormObject(foo);

    // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    DateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd");
    FormUtils.populateFormFromBean(individualForEditing, action, epo, foo, epo.getBadValueMap());

    List cList = new ArrayList();
    cList.add(new IndividualDataPropertyStatementProcessor());
    //cList.add(new SearchReindexer()); // handled for now by SearchReindexingListener on model
    epo.setChangeListenerList(cList);

    epo.getAdditionalDaoMap().put("DataPropertyStatement", myWebappDaoFactory.getDataPropertyStatementDao()); // EntityDatapropProcessor will look for this
    epo.getAdditionalDaoMap().put("DataProperty", myWebappDaoFactory.getDataPropertyDao()); // EntityDatapropProcessor will look for this

    ApplicationBean appBean = vreq.getAppBean();

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/entity_retry.jsp");
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("title", "Individual Editing Form");
    request.setAttribute("css",
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + appBean.getThemeDir() + "css/edit.css\"/>");
    request.setAttribute("scripts", "/js/edit/entityRetry.js");
    // NC Commenting this out for now. Going to pass on DWR for moniker and use jQuery instead
    // request.setAttribute("bodyAttr"," onLoad=\"monikerInit()\"");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Individual");
    setRequestAttributes(request, epo);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("EntityRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:org.openmrs.module.rheapocadapter.impl.HL7MessageTransformer.java

/**
 * @throws DataTypeException//from   www. ja va2 s  .c o  m
 * @see org.openmrs.module.rheapocadapter.service.MessageTransformer#generateMessage(org.openmrs.Patient)
 */
@Override
public String generateMessage(Patient patient, String eventType) {
    try {
        log.info("Start Creating message");
        String implementationId = "";

        try {
            implementationId = (Context.getAdministrationService().getImplementationId()
                    .getImplementationId() != null)
                            ? Context.getAdministrationService().getImplementationId().getImplementationId()
                            : "rwanda000";
        } catch (NullPointerException e) {
            log.error("No Implementation Id  set;");
            implementationId = "rwanda000";
        }
        String fosaid = implementationId.substring(implementationId.indexOf("rwanda") + 6);
        log.info("fosaid" + fosaid);
        ADT_A05 adt = new ADT_A05();

        // Populate the MSH Segment
        MSH mshSegment = adt.getMSH();
        mshSegment.getFieldSeparator().setValue("|");
        mshSegment.getEncodingCharacters().setValue("^~\\&");
        mshSegment.getDateTimeOfMessage().getTime()
                .setValue(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        mshSegment.getSendingApplication().getNamespaceID().setValue(fosaid);
        mshSegment.getSequenceNumber().setValue("123");
        mshSegment.getMessageType().getMessageCode().setValue("ADT");
        mshSegment.getMessageType().getMessageStructure().setValue("ADT_A05");
        if (eventType.equalsIgnoreCase("Update")) {
            mshSegment.getMessageType().getTriggerEvent().setValue("A31");

        } else if (eventType.equalsIgnoreCase("Create")) {
            mshSegment.getMessageType().getTriggerEvent().setValue("A28");
        }

        mshSegment.getVersionID().getVersionID().setValue("2.5");

        // Populate the PID Segment
        PID pid = adt.getPID();
        pid.getPatientName(0).getFamilyName().getSurname().setValue(patient.getFamilyName());
        pid.getPatientName(0).getGivenName().setValue(patient.getGivenName());
        {
            PatientIdentifierType nid = Context.getPatientService().getPatientIdentifierTypeByName("NID");
            PatientIdentifierType mutuelle = Context.getPatientService()
                    .getPatientIdentifierTypeByName("Mutuelle");
            PatientIdentifierType rama = Context.getPatientService().getPatientIdentifierTypeByName("RAMA");
            PatientIdentifierType primaryCare = Context.getPatientService()
                    .getPatientIdentifierTypeByName("Primary Care ID Type");
            String id = "";
            String idType = "";
            int i = 0;
            if (getPatientIdentifierByIdentifierType(patient, nid) != null) {
                log.info("Get NID");
                id = "";
                idType = "";
                idType = RHEAHL7Constants.NID_ID_TYPE;
                id = getPatientIdentifierByIdentifierType(patient, nid).getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (getPatientIdentifierByIdentifierType(patient, rama) != null) {
                log.info("Get Rama");
                id = "";
                idType = "";
                idType = RHEAHL7Constants.RAMA_ID_TYPE;
                id = getPatientIdentifierByIdentifierType(patient, rama).getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (getPatientIdentifierByIdentifierType(patient, mutuelle) != null) {
                log.info("Get Mutuelle");
                id = "";
                idType = "";
                idType = RHEAHL7Constants.MUTUELLE_ID_TYPE;
                id = getPatientIdentifierByIdentifierType(patient, mutuelle).getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (getPatientIdentifierByIdentifierType(patient, primaryCare) != null) {
                log.info("Get OMRS");
                id = "";
                idType = "";
                implementationId = implementationId.toLowerCase();
                fosaid = implementationId.substring(implementationId.indexOf("rwanda") + 6);
                idType = RHEAHL7Constants.OMRS_ID_TYPE_PREFIX + fosaid;
                id = getPatientIdentifierByIdentifierType(patient, primaryCare).getIdentifier();
                log.info("idType " + idType);
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }
            }
            if (!patient.getPatientIdentifier().getIdentifierType().equals(nid)
                    && !patient.getPatientIdentifier().getIdentifierType().equals(rama)
                    && !patient.getPatientIdentifier().getIdentifierType().equals(mutuelle)
                    && !patient.getPatientIdentifier().getIdentifierType().equals(primaryCare)) {
                id = "";
                idType = "";
                log.info("Get " + patient.getPatientIdentifier().getIdentifier());
                idType = patient.getPatientIdentifier().getIdentifierType().getName();
                id = patient.getPatientIdentifier().getIdentifier();
                if (id != "" && idType != "") {

                    pid.getPatientIdentifierList(i).getIDNumber().setValue(id);
                    pid.getPatientIdentifierList(i).getIdentifierTypeCode().setValue(idType);
                    i++;
                }

            }

        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Date dob = patient.getBirthdate();
        Date dod = patient.getDeathDate();
        String dobStr = "";
        String dodStr = "";
        if (dob != null)
            dobStr = df.format(dob);
        if (dod != null)
            dodStr = df.format(dod);

        // Address
        XAD add = pid.getPatientAddress(0);
        add.getCountry().setValue(patient.getPersonAddress().getCountry());
        add.getStateOrProvince().setValue(patient.getPersonAddress().getStateProvince());
        add.getCity().setValue(patient.getPersonAddress().getCountyDistrict());
        add.getCensusTract().setValue(patient.getPersonAddress().getAddress1());
        add.getCountyParishCode().setValue(patient.getPersonAddress().getCityVillage());
        add.getOtherGeographicDesignation().setValue(patient.getPersonAddress().getNeighborhoodCell());

        // gender
        pid.getAdministrativeSex().setValue(patient.getGender());

        // dob
        pid.getDateTimeOfBirth().getTime().setValue(dobStr);

        // Death
        // pid.getPatientDeathIndicator().setValue(
        // patient.getDead().toString());
        // pid.getPatientDeathDateAndTime().getTime().setValue(dodStr);

        PD1 pd1 = adt.getPD1();
        pd1.getStudentIndicator().setTable(0);
        pd1.getHandicap().setTable(0);

        // set mother and father name
        int n = 0;
        NK1 nk1 = adt.getNK1(n);

        PersonAttributeType mother = Context.getPersonService()
                .getPersonAttributeTypeByName(RHEAConstants.MOTHER_NAME_ATTRIBUTE_TYPE);
        PersonAttribute mom = patient.getAttribute(mother);
        if (mom != null) {
            n++;
            String mom_str = mom.getValue();
            nk1.getSetIDNK1().setValue("1");
            nk1.getRelationship().getIdentifier().setValue("MTH");
            nk1.getRelationship().getText().setValue("mother");
            nk1.getRelationship().getNameOfCodingSystem().setValue("REL_RTS");
            nk1.getNKName(0).getFamilyName().getSurname().setValue(mom_str);
        }

        nk1 = adt.getNK1(n);

        PersonAttributeType father = Context.getPersonService()
                .getPersonAttributeTypeByName(RHEAConstants.FATHER_NAME_ATTRIBUTE_TYPE);
        PersonAttribute dad = patient.getAttribute(father);
        if (dad != null) {
            n++;
            String dad_str = dad.getValue();
            nk1.getSetIDNK1().setValue("2");
            nk1.getRelationship().getIdentifier().setValue("FTH");
            nk1.getRelationship().getText().setValue("father");
            nk1.getRelationship().getNameOfCodingSystem().setValue("REL_RTS");
            nk1.getNKName(0).getFamilyName().getSurname().setValue(dad_str);
        }

        PV1 pv1 = adt.getPV1();
        pv1.getSetIDPV1().setValue("1");
        pv1.getPatientClass().setValue("U");

        return new GenericParser().encode(adt, "XML");
    } catch (DataTypeException e) {
        log.error("Error generated" + e.getMessage());
        return "";
    } catch (HL7Exception e) {
        log.error("Error generated" + e.getMessage());
        return "";
    }

}