Example usage for java.util HashMap toString

List of usage examples for java.util HashMap toString

Introduction

In this page you can find the example usage for java.util HashMap toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:it.geosolutions.geocollect.android.core.mission.PendingMissionListFragment.java

/**
 * checks if background data for the current template is available if not, the user is asked to download
 *//*w w w.  j a v a 2s. co  m*/
private void checkIfBackgroundIsAvailableForTemplate() {

    boolean exists = MissionUtils.checkTemplateForBackgroundData(getActivity(), missionTemplate);

    if (!exists) {

        final HashMap<String, Integer> urls = MissionUtils
                .getContentUrlsAndFileAmountForTemplate(missionTemplate);

        if (BuildConfig.DEBUG) {
            Log.i(TAG, "downloading " + urls.toString());
        }

        Resources res = getResources();
        for (String url : urls.keySet()) {

            final String mount = MapFilesProvider.getEnvironmentDirPath(getActivity());

            String dialogMessage = res.getQuantityString(R.plurals.dialog_message_with_amount, urls.get(url),
                    urls.get(url));
            new ZipFileManager(getActivity(), mount, MapFilesProvider.getBaseDir(), url, null, dialogMessage) {
                @Override
                public void launchMainActivity(final boolean success) {

                    // TODO apply ? this was earlier in StartupActivity
                    // if (getActivity().getApplication() instanceof GeoCollectApplication) {
                    // ((GeoCollectApplication) getActivity().getApplication()).setupMBTilesBackgroundConfiguration();
                    // }
                    // launch.putExtra(PendingMissionListFragment.INFINITE_SCROLL, false);
                    if (success) {

                        Toast.makeText(getActivity(), getString(R.string.download_successfull),
                                Toast.LENGTH_SHORT).show();
                    }

                }
            };
        }

    }

}

From source file:edu.cornell.mannlib.vitro.webapp.search.controller.ExternalLookupAutocompleteController.java

public ExternalLookupService getExternalLookupService(String serviceURI, VitroRequest vreq) throws Exception {
    HashMap<String, String> serviceInfo = this.getServiceInformation(serviceURI, vreq);

    if (!serviceInfo.containsKey("serviceClass")) {
        log.error("No service class returned for service URI " + serviceURI);
        throw new Exception("No service class returned for service URI " + serviceURI);
    }//from   www . ja va 2 s. c  om
    String serviceClassURI = serviceInfo.get("serviceClass");
    //URI is of form java:.., need to get portion after java:...
    String serviceClassName = DataGetterUtils.getClassNameFromUri(serviceClassURI);
    if (serviceClassName != null) {
        ExternalLookupService externalServiceClass = null;

        Object object = null;
        try {
            Class classDefinition = Class.forName(serviceClassName);
            object = classDefinition.newInstance();
            externalServiceClass = (ExternalLookupService) object;
        } catch (InstantiationException e) {
            System.out.println(e);
        } catch (IllegalAccessException e) {
            System.out.println(e);
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }

        if (externalServiceClass == null) {
            log.error("could not find Lookup Class for " + serviceClassName);
            return null;
        }

        //Initialize this class
        log.debug("Initializing " + serviceClassName + " with serviceInfo " + serviceInfo.toString());
        externalServiceClass.initializeLookup(serviceInfo);
        return externalServiceClass;

    }

    log.debug("Service class name is null for " + serviceURI + " and no lookup will occur");
    return null;

}

From source file:nl.systemsgenetics.cellTypeSpecificAlleleSpecificExpression.PhasedEntry.java

private Pair<HashMap<String, ArrayList<IndividualSnpData>>, ArrayList<GenomicRegion>> addPhasingToSNPHashMap(
        HashMap<String, ArrayList<IndividualSnpData>> snpHashMap, String couplingLoc,
        ArrayList<GenomicRegion> genomicRegions, String vcfLoc) throws IOException {

    String tabixLoc = vcfLoc + ".tbi";

    VcfGenotypeData genotypeData = new VcfGenotypeData(new File(vcfLoc), new File(tabixLoc),
            GlobalVariables.variantProb);

    //make a Hashmap with the coupling information correct.
    String[] sampleNames = genotypeData.getSampleNames();
    ArrayList<String> couplingList = UtilityMethods.readFileIntoStringArrayList(couplingLoc);

    HashMap<String, Integer> couplingMap = new HashMap<String, Integer>();

    for (String iSample : couplingList) {
        String[] tempCouple = iSample.split("\t");
        boolean found = false;
        for (int i = 0; i < sampleNames.length; i++) {
            if (tempCouple[0].equals(sampleNames[i])) {
                couplingMap.put(tempCouple[1], i);
                found = true;/*from   w ww  .  j a va2 s  .c  om*/
                break;
            }
        }

        if (!found && GlobalVariables.verbosity >= 10) {
            System.out.println("Couldn't find individual " + tempCouple[0]
                    + " in sampleNames, continueing with the next.");
            System.out.println(Arrays.toString(sampleNames));
        }
    }

    if (GlobalVariables.verbosity >= 100) {
        System.out.println("final coupling map:");
        System.out.println(couplingMap.toString());
    }

    int snpsDone = 0;
    for (int regionIndicator = 0; regionIndicator < genomicRegions.size(); regionIndicator++) {

        GenomicRegion iRegion = genomicRegions.get(regionIndicator);

        Iterable<GeneticVariant> VariantsInRegion;
        VariantsInRegion = genotypeData.getVariantsByRange(iRegion.getSequence(), iRegion.getTestStart() - 1, //minus one because bigger than.
                iRegion.getTestEnd());

        ArrayList<String> snpsInThisTestRegion = new ArrayList<String>();

        for (GeneticVariant currentVariant : VariantsInRegion) {

            if (GlobalVariables.verbosity >= 100) {
                System.out.println("Starting " + currentVariant.getPrimaryVariantId());
            }

            if (!(currentVariant.isSnp() && currentVariant.isBiallelic())) {
                //not a valid variant
                if (GlobalVariables.verbosity >= 100) {
                    System.out.println("continueing because not a valid variant");
                }
                continue;
            }

            String snpName = currentVariant.getPrimaryVariantId();
            String chr = currentVariant.getSequenceName();
            String posString = Integer.toString(currentVariant.getStartPos());

            ArrayList<IndividualSnpData> oldSnpData = snpHashMap.get(chr + ":" + posString);

            if (oldSnpData == null) {
                if (GlobalVariables.verbosity >= 100) {
                    System.out.println(
                            "Couldn't find SNP: " + snpName + " in AS reads, continueing with the next.");
                }
                continue;
            }

            if (!oldSnpData.get(0).getSnpName().equals(snpName)) {
                if (GlobalVariables.verbosity >= 10) {
                    System.out.println("Couldn't find SNP: " + snpName + " in the correct position: " + chr
                            + ":" + posString);
                    System.out.println(oldSnpData.get(0).getSnpName());
                }
                continue;
            }

            snpsInThisTestRegion.add(chr + ":" + posString);

            //If phasing is already add to this variant we may as well stop right here.
            if (oldSnpData.get(0).hasPhasing()) {
                //this assumes all individuals in oldSNPdata are phased at the same time.
                //currently this is the case, but if it changes it, it might break.
                continue;
            }

            ArrayList<IndividualSnpData> newSnpData = new ArrayList<IndividualSnpData>();
            List<Boolean> SamplePhasing = currentVariant.getSamplePhasing();
            List<Alleles> Variants = currentVariant.getSampleVariants();

            boolean passSNP = false;

            for (IndividualSnpData iAS : oldSnpData) {
                int i;

                i = couplingMap.get(iAS.getSampleName());

                //make sure there is phasing data available:
                if (SamplePhasing.get(i)) {

                    char Alt = iAS.getAlternative();

                    //Genotype IO used the phasing boolean, and the 
                    //order of the allele characters for the phasing.
                    char[] alleleChars;
                    alleleChars = Variants.get(i).getAllelesAsChars();

                    if (GlobalVariables.verbosity >= 100) {
                        System.out.println(Arrays.toString(alleleChars));
                    }

                    //first assuming the allele is reference
                    //if not the cse, then we change it.
                    int first = 0;
                    int second = 0;

                    if (alleleChars[0] == Alt) {
                        first = 1;
                    }
                    if (alleleChars[1] == Alt) {
                        second = 1;
                    }

                    try {
                        iAS.setPhasing(first, second);
                    } catch (IllegalDataException e) {
                        if (GlobalVariables.verbosity >= 10 && !passSNP) {
                            System.out.println("Did not set phasing for variant" + snpName
                                    + " phasing does not match genotype.");
                        }
                        passSNP = true;

                    }
                }
                newSnpData.add(iAS);
            }

            //something went wrong in the SNP with phasing information and genotype from other data.
            if (passSNP) {
                newSnpData = oldSnpData;
            }

            //overwrite this into the snpHashMap

            snpHashMap.put(chr + ":" + posString, newSnpData);
            snpsDone++;
        }

        iRegion.setSnpInRegions(snpsInThisTestRegion);

        genomicRegions.set(regionIndicator, iRegion);

        if (GlobalVariables.verbosity >= 10 && regionIndicator % 1000 == 0) {
            System.out.println("Finished adding phasing to " + Integer.toString(regionIndicator) + " regions, "
                    + Integer.toString(snpsDone) + " snps.");
        }
    }

    //so I can output it easily
    Pair<HashMap<String, ArrayList<IndividualSnpData>>, ArrayList<GenomicRegion>> returnPair;

    returnPair = new Pair<HashMap<String, ArrayList<IndividualSnpData>>, ArrayList<GenomicRegion>>(snpHashMap,
            genomicRegions);

    return returnPair;
}

From source file:org.hfoss.posit.android.sync.Communicator.java

/**
 * Sends a GPS point and associated data to the Posit server. Called from 
 *  Tracker Activity or TrackerBackgroundService.  
 *//*w  w  w  .  jav a  2s .c  o m*/
public String registerExpeditionPoint(Context context, double lat, double lng, double alt, int swath,
        int expedition, long time) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String server = prefs.getString(SERVER_PREF, "");

    //long swath, int expedition) {
    Log.i(TAG, "Communicator, registerExpeditionPoint " + lat + " " + lng + " " + time);
    HashMap<String, String> sendMap = new HashMap<String, String>();
    addRemoteIdentificationInfo(sendMap);
    Log.i(TAG, "Sendmap= " + sendMap.toString());
    String addExpeditionUrl = server + "/api/addExpeditionPoint?authKey=" + this.getAuthKey(context);
    sendMap.put(DbManager.GPS_POINT_LATITUDE, "" + lat);
    sendMap.put(DbManager.GPS_POINT_LONGITUDE, lng + "");
    sendMap.put(DbManager.GPS_POINT_ALTITUDE, "" + alt);
    sendMap.put(DbManager.GPS_POINT_SWATH, "" + swath);
    sendMap.put(DbManager.EXPEDITION, expedition + "");
    sendMap.put(DbManager.GPS_TIME, time + "");
    Log.i(TAG, "Sendmap= " + sendMap.toString());

    String response = doHTTPPost(addExpeditionUrl, sendMap);
    Log.i(TAG, "Communicator, registerExpeditionPoint, response: " + response);
    return response;
}

From source file:com.quinsoft.zeidon.standardoe.ViewImpl.java

/**
 * This is used to look for memory leaks of EntityInstanceImpl.
 *
 * @return/*from ww w .  j av a 2 s  .c o m*/
 */
int countAllEntities() {
    int count = 0;
    HashSet<EntityInstanceImpl> allEntities = new HashSet<EntityInstanceImpl>();
    HashMap<String, Integer> entities = new HashMap<String, Integer>();
    for (EntityInstanceImpl ei = getObjectInstance().getRootEntityInstance(); ei != null; ei = ei
            .getNextHier()) {
        ei.countAllVersions(allEntities);
        for (EntityInstanceImpl linked : ei.getAllLinkedInstances(true)) {
            if (!allEntities.contains(linked))
                linked.countAllVersions(allEntities);
        }
    }

    for (EntityInstanceImpl ei : allEntities) {
        String name = (ei == null) ? "null" : ei.getEntityDef().getName();
        Integer ec = entities.get(name);
        if (ec == null)
            ec = 1;
        else
            ec = ec + 1;
        entities.put(name, ec);
    }

    count = allEntities.size();
    log().info("Entities = " + entities.toString());
    log().info("Total entities = " + count);
    return count;
}

From source file:com.google.flatbuffers.Table.java

@Override
public String toString() {
    HashMap<String, Object> v = new HashMap<String, Object>();
    try {//from ww  w .j  av  a 2  s  .  co  m
        Method[] ms = this.getClass().getDeclaredMethods();
        for (Method m : ms) {
            String sMethodName = m.getName();
            if (m.getParameterTypes().length == 0 && !sMethodName.endsWith("AsByteBuffer")) {
                if (sMethodName.endsWith("Length")) {
                    int ii = sMethodName.lastIndexOf("Length");
                    String sMethodName1 = sMethodName.substring(0, ii);
                    List<Object> l = new ArrayList<>();
                    int iLength = 0;
                    try {
                        iLength = (int) m.invoke(this, new Object[] {});
                    } catch (Exception e) {
                    }
                    for (int i = 0; i < iLength; i++) {
                        Method m1 = this.getClass().getDeclaredMethod(sMethodName1,
                                new Class<?>[] { Integer.TYPE });
                        Object oKq = m1.invoke(this, new Object[] { i });
                        l.add(oKq);
                    }
                    v.put(sMethodName1, l);
                } else {
                    Object oKq = m.invoke(this, new Object[] {});
                    v.put(sMethodName, oKq);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return v.toString();
}

From source file:org.gbif.ipt.task.GenerateDCAT.java

/**
 * This method loads the DCAT prefixes from dcat.properties.
 *///from  ww w  .j  a v a2  s.  com
private Map<String, String> loadDCATPrefixes() {
    HashMap<String, String> prefixes = new HashMap<String, String>();
    Closer closer = Closer.create();
    try {
        InputStreamUtils streamUtils = new InputStreamUtils();
        InputStream configStream = streamUtils.classpathStream(PREFIXES_PROPERTIES);
        if (configStream == null) {
            LOG.error("Could not load DCAT prefixes from file: " + PREFIXES_PROPERTIES);
        } else {
            Properties properties = new Properties();
            properties.load(configStream);
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                String key = StringUtils.trim((String) entry.getKey());
                String value = StringUtils.trim((String) entry.getValue());
                if (key != null && value != null) {
                    prefixes.put(key, value);
                } else {
                    throw new InvalidConfigException(InvalidConfigException.TYPE.INVALID_PROPERTIES_FILE,
                            "Invalid properties file: " + PREFIXES_PROPERTIES);
                }
            }
            LOG.debug("Loaded DCAT prefixes: " + prefixes.toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            LOG.error("Failed to close input stream on DCAT prefixes file: " + PREFIXES_PROPERTIES);
        }
    }
    return prefixes;
}

From source file:org.restcomm.android.sdk.RCDevice.java

/**
 * Create an outgoing connection to an endpoint. Important: if you work with Android API 23 or above you will need to handle dynamic Android permissions in your Activity
 * as described at https://developer.android.com/training/permissions/requesting.html. More specifically the Restcomm Client SDK needs RECORD_AUDIO, CAMERA (only if the local user
 * has enabled local video via RCConnection.ParameterKeys.CONNECTION_VIDEO_ENABLED; if not then this permission isn't needed), and USE_SIP permission
 * to be able to connect(). For an example of such permission handling you can check MainActivity of restcomm-hello world sample App. Notice that if any of these permissions
 * are missing, the call will fail with a ERROR_CONNECTION_PERMISSION_DENIED error.
 *
 * @param parameters Parameters such as the endpoint we want to connect to, etc. Possible keys: <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_PEER</b>: Who is the called number, like <i>'+1235'</i> or <i>'sip:+1235@cloud.restcomm.com'</i> <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_VIDEO_ENABLED</b>: Whether we want WebRTC video enabled or not. If this is true, then we must provide proper views for CONNECTION_LOCAL_VIDEO and CONNECTION_REMOTE_VIDEO respectively (please check below). If this is false, then CONNECTION_LOCAL_VIDEO and CONNECTION_REMOTE_VIDEO must either not be provided or be null (optional) <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_LOCAL_VIDEO</b>: PercentFrameLayout containing the view where we want the local video to be rendered in. You can check res/layout/activity_main.xml
 *                   in hello-world sample to see the structure required (optional) <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_REMOTE_VIDEO</b>: PercentFrameLayout containing the view where we want the remote video to be rendered. You can check res/layout/activity_main.xml
 *                   in hello-world sample to see the structure required (optional)  <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_PREFERRED_AUDIO_CODEC</b>: Preferred audio codec to use. Default is OPUS. Possible values are enumerated at <i>RCConnection.AudioCodec</i> (optional) <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_PREFERRED_VIDEO_CODEC</b>: Preferred video codec to use. Default is VP8. Possible values are enumerated at <i>RCConnection.VideoCodec</i> (optional) <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_PREFERRED_VIDEO_RESOLUTION</b>: Preferred video resolution to use. Default is HD (1280x720). Possible values are enumerated at <i>RCConnection.VideoResolution</i>  (optional) <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_PREFERRED_VIDEO_FRAME_RATE</b>: Preferred frame rate to use. Default is 30fps. Possible values are enumerated at <i>RCConnection.VideoFrameRate</i> (optional) <br>
 *                   <b>RCConnection.ParameterKeys.CONNECTION_CUSTOM_SIP_HEADERS</b>: An optional HashMap&lt;String,String&gt; of custom SIP headers we want to add. For an example
 *                   please check restcomm-helloworld or restcomm-olympus sample Apps (optional) <br>
 *                   <b>RCConnection.ParameterKeys.DEBUG_CONNECTION_CANDIDATE_TIMEOUT</b>: An optional Integer denoting how long to wait for ICE candidates. Zero means default behaviour which is
 *                   to depend on onIceGatheringComplete from Peer Connection facilities. Any other integer value means to wait at most that amount of time no matter if onIceGatheringComplete has fired.
 *                   The problem we are addressing here is the new Peer Connection ICE gathering timeout which is 40 seconds which is way too long. Notice that the root cause here is in reality
 *                   lack of support for Trickle ICE, so once it is supported we won't be needing such workarounds.
 *                   please check restcomm-helloworld or restcomm-olympus sample Apps (optional) <br>
 * @param listener   The listener object that will receive events when the connection state changes
 * @return An RCConnection object representing the new connection or null in case of error. Error
 * means that RCDevice.state not ready to make a call (this usually means no WiFi available)
 *//*from   w  ww. j  a  v a 2  s  . c o  m*/
public RCConnection connect(HashMap<String, Object> parameters, RCConnectionListener listener)
        throws RCException {
    RCLogger.i(TAG, "connect(): " + parameters.toString());

    RCUtils.validateConnectionParms(parameters);

    if (cachedConnectivityStatus == RCDeviceListener.RCConnectivityStatus.RCConnectivityStatusNone) {
        // Phone state Intents to capture connection failed event
        String username = "";
        if (parameters.get(RCConnection.ParameterKeys.CONNECTION_PEER) != null)
            username = parameters.get(RCConnection.ParameterKeys.CONNECTION_PEER).toString();
        sendQoSNoConnectionIntent(username, this.getConnectivityStatus().toString());
    }

    if (state == DeviceState.READY) {
        RCLogger.i(TAG, "RCDevice.connect(), with connectivity");

        state = DeviceState.BUSY;

        RCConnection connection = new RCConnection.Builder(false, RCConnection.ConnectionState.PENDING, this,
                signalingClient, audioManager).listener(listener)
                        .peer((String) parameters.get(RCConnection.ParameterKeys.CONNECTION_PEER)).build();
        connection.open(parameters);

        // keep connection in the connections hashmap
        connections.put(connection.getId(), connection);

        return connection;
    } else {
        throw new RCException(RCClient.ErrorCodes.ERROR_CONNECTION_DEVICE_NOT_READY);
        //return null;
    }
}

From source file:org.apache.fineract.infrastructure.scheduledemail.service.EmailCampaignWritePlatformCommandHandlerImpl.java

@Override
@CronTarget(jobName = JobName.EXECUTE_EMAIL)
public void sendEmailMessage() throws JobExecutionException {
    if (IPv4Helper.applicationIsNotRunningOnLocalMachine()) { //remove when testing locally
        final List<EmailMessage> emailMessages = this.emailMessageRepository
                .findByStatusType(EmailMessageStatusType.PENDING.getValue()); //retrieve all pending message

        for (final EmailMessage emailMessage : emailMessages) {

            if (isValidEmail(emailMessage.getEmailAddress())) {

                final EmailCampaign emailCampaign = this.emailCampaignRepository
                        .findOne(emailMessage.getEmailCampaign().getId()); //

                final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat
                        .instance(emailCampaign.getEmailAttachmentFileFormat());

                final List<File> attachmentList = new ArrayList<>();

                final StringBuilder errorLog = new StringBuilder();

                //check if email attachment format exist
                if (emailAttachmentFileFormat != null
                        && Arrays.asList(ScheduledEmailAttachmentFileFormat.validValues())
                                .contains(emailAttachmentFileFormat.getId())) {

                    final Report stretchyReport = emailCampaign.getStretchyReport();

                    final String reportName = (stretchyReport != null) ? stretchyReport.getReportName() : null;

                    final HashMap<String, String> reportStretchyParams = this
                            .validateStretchyReportParamMap(emailCampaign.getStretchyReportParamMap());

                    // there is a probability that a client has one or more loans or savings therefore we need to send two or more attachments
                    if (reportStretchyParams.containsKey("selectLoan")
                            || reportStretchyParams.containsKey("loanId")) {
                        //get all ids of the client loans
                        if (emailMessage.getClient() != null) {

                            final List<Loan> loans = this.loanRepository
                                    .findLoanByClientId(emailMessage.getClient().getId());

                            HashMap<String, String> reportParams = this
                                    .replaceStretchyParamsWithActualClientParams(reportStretchyParams,
                                            emailMessage.getClient());

                            for (final Loan loan : loans) {
                                if (loan.isOpen()) { // only send attachment for active loan

                                    if (reportStretchyParams.containsKey("selectLoan")) {

                                        reportParams.put("SelectLoan", loan.getId().toString());

                                    } else if (reportStretchyParams.containsKey("loanId")) {

                                        reportParams.put("loanId", loan.getId().toString());
                                    }/*  w  w w. ja  v a2  s  .  c om*/
                                    File file = this.generateAttachments(emailCampaign,
                                            emailAttachmentFileFormat, reportParams, reportName, errorLog);

                                    if (file != null) {
                                        attachmentList.add(file);
                                    } else {
                                        errorLog.append(reportParams.toString());
                                    }
                                }
                            }

                        }
                    } else if (reportStretchyParams.containsKey("savingId")) {
                        if (emailMessage.getClient() != null) {

                            final List<SavingsAccount> savingsAccounts = this.savingsAccountRepository
                                    .findSavingAccountByClientId(emailMessage.getClient().getId());

                            HashMap<String, String> reportParams = this
                                    .replaceStretchyParamsWithActualClientParams(reportStretchyParams,
                                            emailMessage.getClient());

                            for (final SavingsAccount savingsAccount : savingsAccounts) {

                                if (savingsAccount.isActive()) {

                                    reportParams.put("savingId", savingsAccount.getId().toString());

                                    File file = this.generateAttachments(emailCampaign,
                                            emailAttachmentFileFormat, reportParams, reportName, errorLog);

                                    if (file != null) {
                                        attachmentList.add(file);
                                    } else {
                                        errorLog.append(reportParams.toString());
                                    }
                                }
                            }
                        }
                    } else {
                        if (emailMessage.getClient() != null) {

                            HashMap<String, String> reportParams = this
                                    .replaceStretchyParamsWithActualClientParams(reportStretchyParams,
                                            emailMessage.getClient());

                            File file = this.generateAttachments(emailCampaign, emailAttachmentFileFormat,
                                    reportParams, reportName, errorLog);

                            if (file != null) {
                                attachmentList.add(file);
                            } else {
                                errorLog.append(reportParams.toString());
                            }
                        }
                    }

                }

                final EmailMessageWithAttachmentData emailMessageWithAttachmentData = EmailMessageWithAttachmentData
                        .createNew(emailMessage.getEmailAddress(), emailMessage.getMessage(),
                                emailMessage.getEmailSubject(), attachmentList);

                if (!attachmentList.isEmpty() && attachmentList.size() > 0) { // only send email message if there is an attachment to it

                    this.emailMessageJobEmailService.sendEmailWithAttachment(emailMessageWithAttachmentData);

                    emailMessage.setStatusType(EmailMessageStatusType.SENT.getValue());

                    this.emailMessageRepository.save(emailMessage);
                } else {
                    emailMessage.updateErrorMessage(errorLog.toString());

                    emailMessage.setStatusType(EmailMessageStatusType.FAILED.getValue());

                    this.emailMessageRepository.save(emailMessage);
                }
            }
        }

    }

}

From source file:org.hfoss.posit.android.web.Communicator.java

/**
 * Registers the phone being used with the given server address, email,
 * password and imei./*w  w w .  j  av  a2  s.c o m*/
 * 
 * @param server
 * @param authKey
 * @param imei
 * @return authentication key if successful and null if unsuccessful
 * @throws JSONException
 */
public String loginUser(String server, String email, String password, String imei) {
    String url = server + "/api/login";

    HashMap<String, Object> responseMap = null;
    Log.i(TAG, "loginUser URL=" + url);
    HashMap<String, String> sendMap = new HashMap<String, String>();
    sendMap.put("email", email);
    sendMap.put("password", password);
    sendMap.put("imei", imei);
    try {
        responseString = doHTTPPost(url, sendMap);
        Log.i(TAG, "longinUser response = " + responseString);
        if (responseString.contains("[Error] ")) {
            Utils.showToast(mContext, responseString);
            return Constants.AUTHN_FAILED + ":" + responseString;
        } else {
            ResponseParser parser = new ResponseParser(responseString);
            responseMap = parser.parseObject();
        }
    } catch (Exception e) {
        Log.i(TAG, "longinUser catch clause response = " + responseString);
        Utils.showToast(mContext, e.getMessage() + "");
        return Constants.AUTHN_FAILED + ":" + responseString;
    }
    try {
        if (responseMap.containsKey(ERROR_CODE))
            return responseMap.get(ERROR_CODE) + ":" + responseMap.get(ERROR_MESSAGE);
        else if (responseMap.containsKey(MESSAGE_CODE)) {
            if (responseMap.get(MESSAGE_CODE).equals(Constants.AUTHN_OK)) {
                return Constants.AUTHN_OK + ":" + responseMap.get(MESSAGE);

            }
        } else {
            return Constants.AUTHN_FAILED + ":" + "repsonseMap = " + responseMap.toString(); //"Malformed message from server.";
        }
    } catch (Exception e) {
        Log.e(TAG, "loginUser " + e.getMessage() + " ");
        return Constants.AUTHN_FAILED + ": " + e.getMessage();
    }
    return null;
}