Example usage for java.util HashMap putAll

List of usage examples for java.util HashMap putAll

Introduction

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

Prototype

public void putAll(Map<? extends K, ? extends V> m) 

Source Link

Document

Copies all of the mappings from the specified map to this map.

Usage

From source file:de.innovationgate.wgpublisher.lucene.LuceneManager.java

private void removeFromIndexedDbs(String dbkey) {
    synchronized (_indexedDbs) {
        // copy indexed dbs
        HashMap newIndexedDbs = new HashMap();
        newIndexedDbs.putAll(_indexedDbs);
        // remove in copy
        newIndexedDbs.remove(dbkey);//from  w ww .j  a  va2  s. c  o  m
        // switch maps
        _indexedDbs = newIndexedDbs;
    }
}

From source file:org.apache.ambari.server.controller.KerberosHelperImpl.java

@Override
public KerberosDescriptor getKerberosDescriptor(Cluster cluster) throws AmbariException {
    StackId stackId = cluster.getCurrentStackVersion();

    // -------------------------------
    // Get the default Kerberos descriptor from the stack, which is the same as the value from
    // stacks/:stackName/versions/:version/artifacts/kerberos_descriptor
    KerberosDescriptor defaultDescriptor = ambariMetaInfo.getKerberosDescriptor(stackId.getStackName(),
            stackId.getStackVersion());//  ww w.  j  ava  2  s  .c  o  m
    // -------------------------------

    // Get the user-supplied Kerberos descriptor from cluster/:clusterName/artifacts/kerberos_descriptor
    KerberosDescriptor descriptor = null;

    PredicateBuilder pb = new PredicateBuilder();
    Predicate predicate = pb.begin().property("Artifacts/cluster_name").equals(cluster.getClusterName()).and()
            .property(ArtifactResourceProvider.ARTIFACT_NAME_PROPERTY).equals("kerberos_descriptor").end()
            .toPredicate();

    synchronized (KerberosHelperImpl.class) {
        if (clusterController == null) {
            clusterController = ClusterControllerHelper.getClusterController();
        }
    }

    ResourceProvider artifactProvider = clusterController.ensureResourceProvider(Resource.Type.Artifact);

    Request request = new RequestImpl(Collections.<String>emptySet(),
            Collections.<Map<String, Object>>emptySet(), Collections.<String, String>emptyMap(), null);

    Set<Resource> response = null;
    try {
        response = artifactProvider.getResources(request, predicate);
    } catch (SystemException e) {
        e.printStackTrace();
        throw new AmbariException(
                "An unknown error occurred while trying to obtain the cluster kerberos descriptor", e);
    } catch (UnsupportedPropertyException e) {
        e.printStackTrace();
        throw new AmbariException(
                "An unknown error occurred while trying to obtain the cluster kerberos descriptor", e);
    } catch (NoSuchParentResourceException e) {
        // parent cluster doesn't exist.  shouldn't happen since we have the cluster instance
        e.printStackTrace();
        throw new AmbariException(
                "An unknown error occurred while trying to obtain the cluster kerberos descriptor", e);
    } catch (NoSuchResourceException e) {
        // no descriptor registered, use the default from the stack
    }

    if (response != null && !response.isEmpty()) {
        Resource descriptorResource = response.iterator().next();
        Map<String, Map<String, Object>> propertyMap = descriptorResource.getPropertiesMap();
        if (propertyMap != null) {
            Map<String, Object> artifactData = propertyMap.get(ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY);
            Map<String, Object> artifactDataProperties = propertyMap
                    .get(ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY + "/properties");
            HashMap<String, Object> data = new HashMap<String, Object>();

            if (artifactData != null) {
                data.putAll(artifactData);
            }

            if (artifactDataProperties != null) {
                data.put("properties", artifactDataProperties);
            }

            descriptor = kerberosDescriptorFactory.createInstance(data);
        }
    }
    // -------------------------------

    // -------------------------------
    // Attempt to build and return a composite of the default Kerberos descriptor and the user-supplied
    // Kerberos descriptor. If the default descriptor exists, overlay the user-supplied Kerberos
    // descriptor on top of it (if it exists) and return the composite; else return the user-supplied
    // Kerberos descriptor. If both values are null, null may be returned.
    if (defaultDescriptor == null) {
        return descriptor;
    } else {
        if (descriptor != null) {
            defaultDescriptor.update(descriptor);
        }
        return defaultDescriptor;
    }
    // -------------------------------
}

From source file:org.apache.geode.distributed.internal.DistributionConfigImpl.java

/**
 * Creates a new <code>DistributionConfigImpl</code> with the given non-default configuration
 * properties. See {@link org.apache.geode.distributed.DistributedSystem#connect} for a list of
 * exceptions that may be thrown./*from   ww  w .j  a  v a  2  s  . c  o  m*/
 * 
 * @param nonDefault The configuration properties specified by the caller
 * @param ignoreGemFirePropsFile whether to skip loading distributed system properties from
 *        gemfire.properties file
 * @param isConnected whether to skip Validation for SSL properties and copy of ssl properties to
 *        other ssl properties. This parameter will be used till we provide support for ssl-*
 *        properties.
 *
 * @since GemFire 8.0
 */
public DistributionConfigImpl(Properties nonDefault, boolean ignoreGemFirePropsFile, boolean isConnected) {
    HashMap props = new HashMap();
    if (!ignoreGemFirePropsFile) {// For admin bug #40434
        props.putAll(loadPropertiesFromURL(DistributedSystem.getPropertyFileURL(), false));
    }
    props.putAll(loadPropertiesFromURL(DistributedSystem.getSecurityPropertiesFileURL(), true));

    // Now override values picked up from the file with values passed
    // in from the caller's code
    if (nonDefault != null) {
        props.putAll(nonDefault);
        setSource(nonDefault, ConfigSource.api());
    }
    // Now remove all user defined properties from props.
    for (Object entry : props.entrySet()) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) entry;
        if (((String) ent.getKey()).startsWith(USERDEFINED_PREFIX_NAME)) {
            userDefinedProps.put(ent.getKey(), ent.getValue());
        }
    }
    // Now override values picked up from the file or code with values
    // from the system properties.
    String[] attNames = getAttributeNames();

    // For gemfire.security-* properties, we will need to look at
    // all the system properties instead of looping through attNames
    Set attNameSet = new HashSet();
    for (int index = 0; index < attNames.length; ++index) {
        attNameSet.add(GEMFIRE_PREFIX + attNames[index]);
    }

    /* clone() is a synchronized method for Properties (actually in Hashtable) */
    Properties sysProps = (Properties) System.getProperties().clone();
    Iterator<?> sysPropsIter = sysProps.entrySet().iterator();
    while (sysPropsIter.hasNext()) {
        Map.Entry sysEntry = (Map.Entry) sysPropsIter.next();
        String sysName = (String) sysEntry.getKey();
        if (attNameSet.contains(sysName) || sysName.startsWith(GEMFIRE_PREFIX + SECURITY_PREFIX_NAME)
                || sysName.startsWith(GEMFIRE_PREFIX + SSL_SYSTEM_PROPS_NAME)) {
            String sysValue = (String) sysEntry.getValue();
            if (sysValue != null) {
                String attName = sysName.substring(GEMFIRE_PREFIX.length());
                props.put(attName, sysValue);
                this.sourceMap.put(attName, ConfigSource.sysprop());
            }
        }
    }
    sysProps.clear(); // clearing cloned SysProps

    final Properties overriddenDefaults = ProcessLauncherContext.getOverriddenDefaults();
    if (!overriddenDefaults.isEmpty()) {
        for (String key : overriddenDefaults.stringPropertyNames()) {
            // only apply the overridden default if it's not already specified in props
            final String property = key.substring(ProcessLauncherContext.OVERRIDDEN_DEFAULTS_PREFIX.length());
            if (!props.containsKey((property))) {
                props.put(property, overriddenDefaults.getProperty(key));
                this.sourceMap.put(property, ConfigSource.launcher());
            }
        }
    }

    initialize(props);

    if (securityPeerAuthInit != null && securityPeerAuthInit.length() > 0) {
        System.setProperty(SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTH_INIT, securityPeerAuthInit);
    }
    if (securityPeerAuthenticator != null && securityPeerAuthenticator.length() > 0) {
        System.setProperty(SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTHENTICATOR, securityPeerAuthenticator);
    }

    Iterator iter = security.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        System.setProperty(SECURITY_SYSTEM_PREFIX + (String) entry.getKey(), (String) entry.getValue());
    }
    if (!isConnected) {
        copySSLPropsToServerSSLProps();
        copySSLPropsToJMXSSLProps();
        copyClusterSSLPropsToGatewaySSLProps();
        copySSLPropsToHTTPSSLProps();
    }

    // Make attributes writeable only
    this.modifiable = true;
    validateConfigurationProperties(props);
    validateSSLEnabledComponentsConfiguration();
    // Make attributes read only
    this.modifiable = false;

}

From source file:com.cloud.hypervisor.kvm.resource.LibvirtComputingResource.java

private HashMap<String, HostVmStateReportEntry> getHostVmStateReport() {
    final HashMap<String, HostVmStateReportEntry> vmStates = new HashMap<String, HostVmStateReportEntry>();
    Connect conn = null;/*from  www .j a v a  2  s .  c  o  m*/

    if (_hypervisorType == HypervisorType.LXC) {
        try {
            conn = LibvirtConnection.getConnectionByType(HypervisorType.LXC.toString());
            vmStates.putAll(getHostVmStateReport(conn));
            conn = LibvirtConnection.getConnectionByType(HypervisorType.KVM.toString());
            vmStates.putAll(getHostVmStateReport(conn));
        } catch (final LibvirtException e) {
            s_logger.debug("Failed to get connection: " + e.getMessage());
        }
    }

    if (_hypervisorType == HypervisorType.KVM) {
        try {
            conn = LibvirtConnection.getConnectionByType(HypervisorType.KVM.toString());
            vmStates.putAll(getHostVmStateReport(conn));
        } catch (final LibvirtException e) {
            s_logger.debug("Failed to get connection: " + e.getMessage());
        }
    }

    return vmStates;
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.HistogramListener.java

/**
 * Calculate the detailed statistics/* www  . j a  va2 s  .c o m*/
 * 
 * This will populate the HistogramScoresBean with the data associated with the
 * particular versioned assessment based on the publishedId.
 *
 * Some of this code will change when we move this to Hibernate persistence.
 * @param publishedId String
 * @param histogramScores TotalScoresBean
 * @return boolean true if successful
 */
public boolean histogramScores(HistogramScoresBean histogramScores, TotalScoresBean totalScores) {
    DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery");
    String publishedId = totalScores.getPublishedId();
    if (publishedId.equals("0")) {
        publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId");
    }
    String actionString = ContextUtil.lookupParam("actionString");
    // See if this can fix SAK-16437
    if (actionString != null && !actionString.equals("reviewAssessment")) {
        // Shouldn't come to here. The action should either be null or reviewAssessment.
        // If we can confirm this is where causes SAK-16437, ask UX for a new screen with warning message.  
        log.error("SAK-16437 happens!! publishedId = " + publishedId + ", agentId = "
                + AgentFacade.getAgentString());
    }

    ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    ResourceLoader rbEval = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    String assessmentName = "";

    histogramScores.clearLowerQuartileStudents();
    histogramScores.clearUpperQuartileStudents();

    String which = histogramScores.getAllSubmissions();
    if (which == null && totalScores.getAllSubmissions() != null) {
        // use totalscore's selection
        which = totalScores.getAllSubmissions();
        histogramScores.setAllSubmissions(which); // changed submission pulldown
    }

    histogramScores.setItemId(ContextUtil.lookupParam("itemId"));
    histogramScores.setHasNav(ContextUtil.lookupParam("hasNav"));

    GradingService delegate = new GradingService();
    PublishedAssessmentService pubService = new PublishedAssessmentService();
    List<AssessmentGradingData> allscores = delegate.getTotalScores(publishedId, which);
    //set the ItemGradingData manually here. or we cannot
    //retrieve it later.
    for (AssessmentGradingData agd : allscores) {
        agd.setItemGradingSet(delegate.getItemGradingSet(String.valueOf(agd.getAssessmentGradingId())));
    }
    if (allscores.isEmpty()) {
        // Similar case in Bug 1537, but clicking Statistics link instead of assignment title.
        // Therefore, redirect the the same page.
        delivery.setOutcome("reviewAssessmentError");
        delivery.setActionString(actionString);
        return true;
    }

    histogramScores.setPublishedId(publishedId);
    int callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER;
    String isFromStudent = (String) ContextUtil.lookupParam("isFromStudent");
    if (isFromStudent != null && "true".equals(isFromStudent)) {
        callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER_STUDENT;
    }

    // get the Map of all users(keyed on userid) belong to the selected sections 
    // now we only include scores of users belong to the selected sections
    Map useridMap = null;
    ArrayList scores = new ArrayList();
    // only do section filter if it's published to authenticated users
    if (totalScores.getReleaseToAnonymous()) {
        scores.addAll(allscores);
    } else {
        useridMap = totalScores.getUserIdMap(callerName);
        Iterator allscores_iter = allscores.iterator();
        while (allscores_iter.hasNext()) {
            AssessmentGradingData data = (AssessmentGradingData) allscores_iter.next();
            String agentid = data.getAgentId();
            if (useridMap.containsKey(agentid)) {
                scores.add(data);
            }
        }
    }
    Iterator iter = scores.iterator();
    //log.info("Has this many agents: " + scores.size());

    if (!iter.hasNext()) {
        log.info("Students who have submitted may have been removed from this site");
        return false;
    }

    // here scores contain AssessmentGradingData 
    Map assessmentMap = getAssessmentStatisticsMap(scores);

    /*
     * find students in upper and lower quartiles 
     * of assessment scores
     */
    ArrayList submissionsSortedForDiscrim = new ArrayList(scores);
    boolean anonymous = Boolean.valueOf(totalScores.getAnonymous()).booleanValue();
    Collections.sort(submissionsSortedForDiscrim,
            new AssessmentGradingComparatorByScoreAndUniqueIdentifier(anonymous));
    int numSubmissions = scores.size();
    //int percent27 = ((numSubmissions*10*27/100)+5)/10; // rounded
    int percent27 = numSubmissions * 27 / 100; // rounded down
    if (percent27 == 0)
        percent27 = 1;
    for (int i = 0; i < percent27; i++) {
        histogramScores.addToLowerQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(i)).getAgentId());
        histogramScores.addToUpperQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(numSubmissions - 1 - i)).getAgentId());
    }

    PublishedAssessmentIfc pub = (PublishedAssessmentIfc) pubService.getPublishedAssessment(publishedId, false);

    if (pub != null) {
        if (actionString != null && actionString.equals("reviewAssessment")) {
            if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) {
                // Bug 1547: If this is during review and the assessment is retracted for edit now, 
                // set the outcome to isRetractedForEdit2 error page.
                delivery.setOutcome("isRetractedForEdit2");
                delivery.setActionString(actionString);
                return true;
            } else {
                delivery.setOutcome("histogramScores");
                delivery.setSecureDeliveryHTMLFragment("");
                delivery.setBlockDelivery(false);
                SecureDeliveryServiceAPI secureDelivery = SamigoApiFactory.getInstance()
                        .getSecureDeliveryServiceAPI();
                if (secureDelivery.isSecureDeliveryAvaliable()) {

                    String moduleId = pub.getAssessmentMetaDataByLabel(SecureDeliveryServiceAPI.MODULE_KEY);
                    if (moduleId != null && !SecureDeliveryServiceAPI.NONE_ID.equals(moduleId)) {

                        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                                .getExternalContext().getRequest();
                        PhaseStatus status = secureDelivery.validatePhase(moduleId, Phase.ASSESSMENT_REVIEW,
                                pub, request);
                        delivery.setSecureDeliveryHTMLFragment(secureDelivery.getHTMLFragment(moduleId, pub,
                                request, Phase.ASSESSMENT_REVIEW, status, new ResourceLoader().getLocale()));
                        if (PhaseStatus.FAILURE == status) {
                            delivery.setOutcome("secureDeliveryError");
                            delivery.setActionString(actionString);
                            delivery.setBlockDelivery(true);
                            return true;
                        }
                    }
                }
            }
        }

        boolean showObjectivesColumn = Boolean
                .parseBoolean(pub.getAssessmentMetaDataByLabel(AssessmentBaseIfc.HASMETADATAFORQUESTIONS));
        Map<String, Double> objectivesCorrect = new HashMap<String, Double>();
        Map<String, Integer> objectivesCounter = new HashMap<String, Integer>();
        Map<String, Double> keywordsCorrect = new HashMap<String, Double>();
        Map<String, Integer> keywordsCounter = new HashMap<String, Integer>();

        assessmentName = pub.getTitle();

        List<? extends SectionDataIfc> parts = pub.getSectionArraySorted();
        histogramScores.setAssesmentParts((List<PublishedSectionData>) parts);
        ArrayList info = new ArrayList();
        Iterator partsIter = parts.iterator();
        int secseq = 1;
        double totalpossible = 0;
        boolean hasRandompart = false;
        boolean isRandompart = false;
        String poolName = null;

        HashMap itemScoresMap = delegate.getItemScores(Long.valueOf(publishedId), Long.valueOf(0), which);
        HashMap itemScores = new HashMap();

        if (totalScores.getReleaseToAnonymous()) {
            // skip section filter if it's published to anonymous users
            itemScores.putAll(itemScoresMap);
        } else {
            if (useridMap == null) {
                useridMap = totalScores.getUserIdMap(callerName);
            }

            for (Iterator it = itemScoresMap.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                Long itemId = (Long) entry.getKey();
                ArrayList itemScoresList = (ArrayList) entry.getValue();

                ArrayList filteredItemScoresList = new ArrayList();
                Iterator itemScoresIter = itemScoresList.iterator();
                // get the Map of all users(keyed on userid) belong to the
                // selected sections

                while (itemScoresIter.hasNext()) {
                    ItemGradingData idata = (ItemGradingData) itemScoresIter.next();
                    String agentid = idata.getAgentId();
                    if (useridMap.containsKey(agentid)) {
                        filteredItemScoresList.add(idata);
                    }
                }
                itemScores.put(itemId, filteredItemScoresList);
            }
        }

        // Iterate through the assessment parts
        while (partsIter.hasNext()) {
            SectionDataIfc section = (SectionDataIfc) partsIter.next();
            String authortype = section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE);
            try {
                if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(Integer.valueOf(authortype))) {
                    hasRandompart = true;
                    isRandompart = true;
                    poolName = section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW);
                } else {
                    isRandompart = false;
                    poolName = null;
                }
            } catch (NumberFormatException e) {
                isRandompart = false;
                poolName = null;
            }
            if (section.getSequence() == null)
                section.setSequence(Integer.valueOf(secseq++));
            String title = rb.getString("part") + " " + section.getSequence().toString();
            title += ", " + rb.getString("question") + " ";
            List<ItemDataIfc> itemset = section.getItemArraySortedForGrading();
            int seq = 1;
            Iterator<ItemDataIfc> itemsIter = itemset.iterator();

            // Iterate through the assessment questions (items)
            while (itemsIter.hasNext()) {
                HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean();
                questionScores.setNumberOfParts(parts.size());
                //if this part is a randompart , then set randompart = true
                questionScores.setRandomType(isRandompart);
                questionScores.setPoolName(poolName);
                ItemDataIfc item = itemsIter.next();

                if (showObjectivesColumn) {
                    String obj = item.getItemMetaDataByLabel(ItemMetaDataIfc.OBJECTIVE);
                    questionScores.setObjectives(obj);
                    String key = item.getItemMetaDataByLabel(ItemMetaDataIfc.KEYWORD);
                    questionScores.setKeywords(key);
                }

                //String type = delegate.getTextForId(item.getTypeId());
                String type = getType(item.getTypeId().intValue());
                if (item.getSequence() == null)
                    item.setSequence(Integer.valueOf(seq++));

                questionScores.setPartNumber(section.getSequence().toString());
                //set the question label depending on random pools and parts
                if (questionScores.getRandomType() && poolName != null) {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part_pool", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_pool", null));
                    }
                } else {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question", null));
                    }
                }
                questionScores.setQuestionNumber(item.getSequence().toString());
                questionScores.setItemId(item.getItemId());
                questionScores.setTitle(title + item.getSequence().toString() + " (" + type + ")");

                if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) { // emi question
                    questionScores.setQuestionText(item.getLeadInText());
                } else {
                    questionScores.setQuestionText(item.getText());
                }

                questionScores.setQuestionType(item.getTypeId().toString());
                //totalpossible = totalpossible + item.getScore().doubleValue();
                //ArrayList responses = null;

                //for each question (item) in the published assessment's current part/section
                determineResults(pub, questionScores, (ArrayList) itemScores.get(item.getItemId()));
                questionScores.setTotalScore(item.getScore().toString());

                questionScores.setN("" + numSubmissions);
                questionScores.setItemId(item.getItemId());
                Set studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect();
                Set studentsResponded = questionScores.getStudentsResponded();
                if (studentsWithAllCorrect == null || studentsResponded == null
                        || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) {
                    questionScores.setPercentCorrectFromUpperQuartileStudents("0");
                    questionScores.setPercentCorrectFromLowerQuartileStudents("0");
                    questionScores.setDiscrimination("0.0");
                } else {
                    int percent27ForThisQuestion = percent27;
                    Set<String> upperQuartileStudents = histogramScores.getUpperQuartileStudents().keySet();
                    Set<String> lowerQuartileStudents = histogramScores.getLowerQuartileStudents().keySet();
                    if (isRandompart) {
                        //we need to calculate the 27% upper and lower
                        //per question for the people that actually answered
                        //this question.
                        upperQuartileStudents = new HashSet<String>();
                        lowerQuartileStudents = new HashSet<String>();
                        percent27ForThisQuestion = questionScores.getNumResponses() * 27 / 100;
                        if (percent27ForThisQuestion == 0)
                            percent27ForThisQuestion = 1;
                        if (questionScores.getNumResponses() != 0) {
                            //need to only get gradings for students that answered this question
                            List<AssessmentGradingData> filteredGradings = filterGradingData(
                                    submissionsSortedForDiscrim, questionScores.getItemId());

                            // SAM-2228: loop control issues because of unsynchronized collection access
                            int filteredGradingsSize = filteredGradings.size();
                            percent27ForThisQuestion = filteredGradingsSize * 27 / 100;

                            for (int i = 0; i < percent27ForThisQuestion; i++) {
                                lowerQuartileStudents
                                        .add(((AssessmentGradingData) filteredGradings.get(i)).getAgentId());
                                //
                                upperQuartileStudents.add(((AssessmentGradingData) filteredGradings
                                        .get(filteredGradingsSize - 1 - i)).getAgentId());
                            }
                        }
                    }
                    if (questionScores.getNumResponses() != 0) {
                        int numStudentsWithAllCorrectFromUpperQuartile = 0;
                        int numStudentsWithAllCorrectFromLowerQuartile = 0;
                        Iterator studentsIter = studentsWithAllCorrect.iterator();
                        while (studentsIter.hasNext()) {
                            String agentId = (String) studentsIter.next();
                            if (upperQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromUpperQuartile++;
                            }
                            if (lowerQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromLowerQuartile++;
                            }
                        }

                        double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        questionScores.setPercentCorrectFromUpperQuartileStudents(
                                Integer.toString((int) percentCorrectFromUpperQuartileStudents));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(
                                Integer.toString((int) percentCorrectFromLowerQuartileStudents));

                        double discrimination = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                - (double) numStudentsWithAllCorrectFromLowerQuartile)
                                / (double) percent27ForThisQuestion;

                        // round to 2 decimals
                        if (discrimination > 999999 || discrimination < -999999) {
                            questionScores.setDiscrimination("NaN");
                        } else {
                            discrimination = ((int) (discrimination * 100.00d)) / 100.00d;
                            questionScores.setDiscrimination(Double.toString(discrimination));
                        }
                    } else {
                        questionScores.setPercentCorrectFromUpperQuartileStudents(rbEval.getString("na"));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(rbEval.getString("na"));
                        questionScores.setDiscrimination(rbEval.getString("na"));
                    }
                }

                info.add(questionScores);
            } // end-while - items

            totalpossible = pub.getTotalScore().doubleValue();

        } // end-while - parts
        histogramScores.setInfo(info);
        histogramScores.setRandomType(hasRandompart);

        int maxNumOfAnswers = 0;
        List<HistogramQuestionScoresBean> detailedStatistics = new ArrayList<HistogramQuestionScoresBean>();
        Iterator infoIter = info.iterator();
        while (infoIter.hasNext()) {
            HistogramQuestionScoresBean questionScores = (HistogramQuestionScoresBean) infoIter.next();
            if (questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MATCHING.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString())
                    || questionScores.getQuestionType()
                            .equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString())
                    || questionScores.getQuestionType().equals("16")) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(true);
                detailedStatistics.add(questionScores);
                if (questionScores.getHistogramBars() != null) {
                    maxNumOfAnswers = questionScores.getHistogramBars().length > maxNumOfAnswers
                            ? questionScores.getHistogramBars().length
                            : maxNumOfAnswers;
                }
            }

            if (showObjectivesColumn) {
                // Get the percentage correct by objective
                String obj = questionScores.getObjectives();
                if (obj != null && !"".equals(obj)) {
                    String[] objs = obj.split(",");
                    for (int i = 0; i < objs.length; i++) {

                        // SAM-2508 set a default value to avoid the NumberFormatException issues
                        Double pctCorrect = 0.0d;
                        Double newAvg = 0.0d;
                        int divisor = 1;

                        try {
                            if (questionScores.getPercentCorrect() != null
                                    && !"N/A".equalsIgnoreCase(questionScores.getPercentCorrect())) {
                                pctCorrect = Double.parseDouble(questionScores.getPercentCorrect());
                            }
                        } catch (NumberFormatException nfe) {
                            log.error("NFE when looking at metadata and objectives", nfe);
                        }

                        if (objectivesCorrect.get(objs[i]) != null) {
                            Double objCorrect = objectivesCorrect.get(objs[i]);
                            divisor = objCorrect.intValue() + 1;

                            newAvg = objCorrect + ((pctCorrect - objCorrect) / divisor);
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        } else {
                            newAvg = new BigDecimal(pctCorrect).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        }

                        objectivesCounter.put(objs[i], divisor);
                        objectivesCorrect.put(objs[i], newAvg);
                    }
                }

                // Get the percentage correct by keyword
                String key = questionScores.getKeywords();
                if (key != null && !"".equals(key)) {
                    String[] keys = key.split(",");
                    for (int i = 0; i < keys.length; i++) {
                        if (keywordsCorrect.get(keys[i]) != null) {
                            int divisor = keywordsCounter.get(keys[i]) + 1;
                            Double newAvg = keywordsCorrect.get(keys[i])
                                    + ((Double.parseDouble(questionScores.getPercentCorrect())
                                            - keywordsCorrect.get(keys[i])) / divisor);

                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], divisor);
                            keywordsCorrect.put(keys[i], newAvg);
                        } else {
                            Double newAvg = Double.parseDouble(questionScores.getPercentCorrect());
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], 1);
                            keywordsCorrect.put(keys[i], newAvg);
                        }
                    }
                }
            }

            //i.e. for EMI questions we add detailed stats for the whole
            //question as well as for the sub-questions
            if (questionScores.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(false);
                detailedStatistics.addAll(questionScores.getInfo());

                Iterator subInfoIter = questionScores.getInfo().iterator();
                while (subInfoIter.hasNext()) {
                    HistogramQuestionScoresBean subQuestionScores = (HistogramQuestionScoresBean) subInfoIter
                            .next();
                    if (subQuestionScores.getHistogramBars() != null) {
                        subQuestionScores.setN(questionScores.getN());
                        maxNumOfAnswers = subQuestionScores.getHistogramBars().length > maxNumOfAnswers
                                ? subQuestionScores.getHistogramBars().length
                                : maxNumOfAnswers;
                    }
                }
                /*                 
                                 Object numberOfStudentsWithZeroAnswers = numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId());
                                 if (numberOfStudentsWithZeroAnswers == null) {
                                    questionScores.setNumberOfStudentsWithZeroAnswers(0);
                                 }
                                 else {
                                    questionScores.setNumberOfStudentsWithZeroAnswers( ((Integer) numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId())).intValue() );
                                 }
                */
            }

        }
        //VULA-1948: sort the detailedStatistics list by Question Label
        sortQuestionScoresByLabel(detailedStatistics);
        histogramScores.setDetailedStatistics(detailedStatistics);
        histogramScores.setMaxNumberOfAnswers(maxNumOfAnswers);
        histogramScores.setShowObjectivesColumn(showObjectivesColumn);

        if (showObjectivesColumn) {
            List<Entry<String, Double>> objectivesList = new ArrayList<Entry<String, Double>>(
                    objectivesCorrect.entrySet());
            Collections.sort(objectivesList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setObjectives(objectivesList);

            List<Entry<String, Double>> keywordsList = new ArrayList<Entry<String, Double>>(
                    keywordsCorrect.entrySet());

            Collections.sort(keywordsList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setKeywords(keywordsList);
        }

        // test to see if it gets back empty map
        if (assessmentMap.isEmpty()) {
            histogramScores.setNumResponses(0);
        }

        try {
            BeanUtils.populate(histogramScores, assessmentMap);

            // quartiles don't seem to be working, workaround
            histogramScores.setQ1((String) assessmentMap.get("q1"));
            histogramScores.setQ2((String) assessmentMap.get("q2"));
            histogramScores.setQ3((String) assessmentMap.get("q3"));
            histogramScores.setQ4((String) assessmentMap.get("q4"));
            histogramScores.setTotalScore((String) assessmentMap.get("totalScore"));
            histogramScores.setTotalPossibleScore(Double.toString(totalpossible));
            HistogramBarBean[] bars = new HistogramBarBean[histogramScores.getColumnHeight().length];
            for (int i = 0; i < histogramScores.getColumnHeight().length; i++) {
                bars[i] = new HistogramBarBean();
                bars[i].setColumnHeight(Integer.toString(histogramScores.getColumnHeight()[i]));
                bars[i].setNumStudents(histogramScores.getNumStudentCollection()[i]);
                bars[i].setRangeInfo(histogramScores.getRangeCollection()[i]);
                //log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]);
            }
            histogramScores.setHistogramBars(bars);

            ///////////////////////////////////////////////////////////
            // START DEBUGGING
            /*
              log.info("TESTING ASSESSMENT MAP");
              log.info("assessmentMap: =>");
              log.info(assessmentMap);
              log.info("--------------------------------------------");
              log.info("TESTING TOTALS HISTOGRAM FORM");
              log.info(
              "HistogramScoresForm Form: =>\n" + "bean.getMean()=" +
              bean.getMean() + "\n" +
              "bean.getColumnHeight()[0] (first elem)=" +
              bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" +
              bean.getInterval() + "\n" + "bean.getLowerQuartile()=" +
              bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" +
              bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() +
              "\n" + "bean.getMedian()=" + bean.getMedian() + "\n" +
              "bean.getNumResponses()=" + bean.getNumResponses() + "\n" +
              "bean.getNumStudentCollection()=" +
              bean.getNumStudentCollection() +
              "\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" +
              bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" +
              "bean.getQ4()=" + bean.getQ4());
              log.info("--------------------------------------------");
                    
             */
            // END DEBUGGING CODE
            ///////////////////////////////////////////////////////////
        } catch (IllegalAccessException e) {
            log.warn("IllegalAccessException:  unable to populate bean" + e);
        } catch (InvocationTargetException e) {
            log.warn("InvocationTargetException: unable to populate bean" + e);
        }

        histogramScores.setAssessmentName(assessmentName);
    } else {
        log.error("pub is null. publishedId = " + publishedId);
        return false;
    }
    return true;
}

From source file:de.intranda.goobi.plugins.CSICMixedImport.java

private List<Record> retrieveOriginalRecordsFromFile() {

    List<Record> recordList = new ArrayList<Record>();
    HashMap<String, String> filteredRecordStrings = new HashMap<String, String>();
    int count = 0;

    if (importFile.getName().endsWith("zip")) {
        logger.info("Extracting zip archive");
        HashMap<String, byte[]> recordStrings = unzipFile(importFile);
        // Check all records first to see what's inside
        for (String key : recordStrings.keySet()) {
            byte[] bytes = recordStrings.get(key);
            InputStream bais = null;
            if (key.endsWith(".zip")) {
                // Another zip-archive
                logger.debug("Extracting inner archive " + key + "; size = " + bytes.length + " bytes");
                try {
                    bais = new ByteArrayInputStream(bytes);
                    // FileOutputStream fout = new FileOutputStream(new File(importFolder, "temp.zip"));
                    // fout.write(bytes);
                    // fout.close();
                    HashMap<String, String> tempRecords = unzipStream(bais);
                    filteredRecordStrings.putAll(tempRecords);
                } catch (Exception e) {
                    logger.error("Unable to read inner zip file");
                } finally {
                    if (bais != null) {
                        try {
                            bais.close();
                        } catch (IOException e) {
                            logger.error(e);
                        }/*from w ww .ja va  2  s .  com*/
                    }
                }
            } else if (key.endsWith(".xml")) {
                BufferedReader br = null;
                // ByteArrayInputStream bais = null;
                InputStreamReader isr = null;
                try {
                    bais = new ByteArrayInputStream(bytes);
                    isr = new InputStreamReader(bais);
                    br = new BufferedReader(isr);
                    StringBuffer sb = new StringBuffer();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line).append("\n");
                    }
                    filteredRecordStrings.put(key, sb.toString());
                } catch (IOException e) {
                    logger.error("Unable to read METS file from zip-Archive");
                } finally {
                    try {
                        if (bais != null) {
                            bais.close();
                        }
                        if (isr != null) {
                            isr.close();
                        }
                        if (br != null) {
                            br.close();
                        }
                    } catch (IOException e) {
                        logger.error("Error closing String reader");
                    }
                }
            }
        }

        for (String key : filteredRecordStrings.keySet()) {
            if (!key.endsWith(".xml")) {
                continue;
            }
            String importFileName = key;
            String importData = filteredRecordStrings.get(key);
            logger.debug("Extracting record " + ++count);
            Record rec = new Record();
            // System.out.println("Data from Zip-File:\n " + importData);
            rec.setData(importData);
            logger.debug("Getting record " + importFileName);
            rec.setId(importFileName.substring(0, importFileName.indexOf(".")));
            recordList.add(rec);
        }
    } else {
        logger.info("Importing single record file");
        InputStream input = null;
        StringWriter writer = null;
        try {
            logger.debug("loaded file: " + importFile.getAbsolutePath());
            String importFileName = importFile.getName();
            input = new FileInputStream(importFile);
            Record rec = new Record();
            writer = new StringWriter();
            IOUtils.copy(input, writer, encoding);
            rec.setData(writer.toString());
            rec.setId(importFileName.substring(0, importFileName.indexOf(".")));
            recordList.add(rec);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (input != null) {
                try {
                    if (writer != null)
                        writer.close();
                    input.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
    return recordList;

}

From source file:org.apache.rampart.builder.SymmetricBindingBuilder.java

private void doEncryptBeforeSig(RampartMessageData rmd) throws RampartException {

    long t0 = 0, t1 = 0, t2 = 0;

    RampartPolicyData rpd = rmd.getPolicyData();

    Vector signatureValues = new Vector();

    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }/*ww  w.  j a  v a2s .co  m*/

    Token encryptionToken = rpd.getEncryptionToken();
    Vector encrParts = RampartUtil.getEncryptedParts(rmd);

    Vector sigParts = RampartUtil.getSignedParts(rmd);

    if (encryptionToken == null && encrParts.size() > 0) {
        throw new RampartException("encryptionTokenMissing");
    }

    if (encryptionToken != null && encrParts.size() > 0) {
        // The encryption token can be an IssuedToken or a
        // SecureConversationToken
        String tokenId = null;
        org.apache.rahas.Token tok = null;

        if (encryptionToken instanceof IssuedToken) {
            tokenId = rmd.getIssuedEncryptionTokenId();
            if (log.isDebugEnabled()) {
                log.debug("Issued EncryptionToken Id : " + tokenId);
            }
        } else if (encryptionToken instanceof SecureConversationToken) {
            tokenId = rmd.getSecConvTokenId();
            if (log.isDebugEnabled()) {
                log.debug("SCT Id : " + tokenId);
            }
        } else if (encryptionToken instanceof X509Token) {
            if (rmd.isInitiator()) {
                tokenId = setupEncryptedKey(rmd, encryptionToken);
            } else {
                tokenId = getEncryptedKey(rmd);
            }
        } // TODO SAMLToken

        if (tokenId == null || tokenId.length() == 0) {
            throw new RampartException("noSecurityToken");
        }

        // Hack to handle reference id issues
        // TODO Need a better fix
        if (tokenId.startsWith("#")) {
            tokenId = tokenId.substring(1);
        }

        /*
         * Get hold of the token from the token storage
         */
        tok = this.getToken(rmd, tokenId);

        /*
         * Attach the token into the message based on token inclusion values
         */
        boolean attached = false;
        Element encrTokenElement = null;
        Element refList = null;
        WSSecDKEncrypt dkEncr = null;
        WSSecEncrypt encr = null;
        Element encrDKTokenElem = null;

        if (SPConstants.INCLUDE_TOEKN_ALWAYS == encryptionToken.getInclusion()
                || SPConstants.INCLUDE_TOKEN_ONCE == encryptionToken.getInclusion() || (rmd.isInitiator()
                        && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encryptionToken.getInclusion())) {
            encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
            attached = true;
        } else if (encryptionToken instanceof X509Token && rmd.isInitiator()) {
            encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
        }

        Document doc = rmd.getDocument();

        AlgorithmSuite algorithmSuite = rpd.getAlgorithmSuite();
        if (encryptionToken.isDerivedKeys()) {
            log.debug("Use drived keys");

            dkEncr = new WSSecDKEncrypt();

            if (attached && tok.getAttachedReference() != null) {

                dkEncr.setExternalKey(tok.getSecret(),
                        (Element) doc.importNode((Element) tok.getAttachedReference(), true));

            } else if (tok.getUnattachedReference() != null) {
                dkEncr.setExternalKey(tok.getSecret(),
                        (Element) doc.importNode((Element) tok.getUnattachedReference(), true));
            } else {
                dkEncr.setExternalKey(tok.getSecret(), tok.getId());
            }
            try {
                dkEncr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                dkEncr.setDerivedKeyLength(algorithmSuite.getEncryptionDerivedKeyLength() / 8);
                dkEncr.prepare(doc);
                encrDKTokenElem = dkEncr.getdktElement();
                RampartUtil.appendChildToSecHeader(rmd, encrDKTokenElem);

                refList = dkEncr.encryptForExternalRef(null, encrParts);

            } catch (WSSecurityException e) {
                throw new RampartException("errorInDKEncr");
            } catch (ConversationException e) {
                throw new RampartException("errorInDKEncr");
            }
        } else {
            log.debug("NO derived keys, use the shared secret");
            encr = new WSSecEncrypt();

            encr.setWsConfig(rmd.getConfig());
            encr.setEncKeyId(tokenId);
            RampartUtil.setEncryptionUser(rmd, encr);
            encr.setEphemeralKey(tok.getSecret());
            encr.setDocument(doc);
            encr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
            // SymmKey is already encrypted, no need to do it again
            encr.setEncryptSymmKey(false);
            if (!rmd.isInitiator() && tok instanceof EncryptedKeyToken) {
                encr.setUseKeyIdentifier(true);
                encr.setCustomReferenceValue(((EncryptedKeyToken) tok).getSHA1());
                encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
            }

            try {

                encr.prepare(doc,
                        RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(), rmd.getCustomClassLoader()));
                // Encrypt, get hold of the ref list and add it
                refList = encr.encryptForExternalRef(null, encrParts);
            } catch (WSSecurityException e) {
                throw new RampartException("errorInEncryption", e);
            }
        }

        this.mainRefListElement = RampartUtil.appendChildToSecHeader(rmd, refList);

        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }

        // Sometimes encryption token is not included in the the message
        if (encrTokenElement != null) {
            this.setInsertionLocation(encrTokenElement);
        } else if (timestampElement != null) {
            this.setInsertionLocation(timestampElement);
        }

        RampartUtil.handleEncryptedSignedHeaders(encrParts, sigParts, doc);

        HashMap sigSuppTokMap = null;
        HashMap endSuppTokMap = null;
        HashMap sgndEndSuppTokMap = null;
        HashMap sgndEncSuppTokMap = null;
        HashMap endEncSuppTokMap = null;
        HashMap sgndEndEncSuppTokMap = null;

        if (this.timestampElement != null) {
            sigParts.add(
                    new WSEncryptionPart(RampartUtil.addWsuIdToElement((OMElement) this.timestampElement)));
        }

        if (rmd.isInitiator()) {

            // Now add the supporting tokens
            SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
            sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);

            SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
            endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);

            SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
            sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);

            SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
            sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);

            SupportingToken endorsingEncryptedSuppTokens = rpd.getEndorsingEncryptedSupportingTokens();
            endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);

            SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();
            sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);

            Vector supportingToks = rpd.getSupportingTokensList();
            for (int i = 0; i < supportingToks.size(); i++) {
                this.handleSupportingTokens(rmd, (SupportingToken) supportingToks.get(i));
            }

            SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
            this.handleSupportingTokens(rmd, encryptedSupportingToks);

            // Setup signature parts
            sigParts = addSignatureParts(sigSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);

        } else {
            addSignatureConfirmation(rmd, sigParts);
        }

        // Sign the message
        // We should use the same key in the case of EncryptBeforeSig
        if (sigParts.size() > 0) {
            signatureValues.add(this.doSymmSignature(rmd, encryptionToken, tok, sigParts));
            this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) this.getInsertionLocation());
        }

        if (rmd.isInitiator()) {

            endSuppTokMap.putAll(endEncSuppTokMap);
            // Do endorsed signatures
            Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
            for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }

            sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
            // Do signed endorsing signatures
            Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
            for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }
        }

        if (tlog.isDebugEnabled()) {
            t2 = System.currentTimeMillis();
            tlog.debug("Encryption took :" + (t1 - t0) + ", Signature tool :" + (t2 - t1));
        }

        // Check for signature protection and encryption of UsernameToken
        if (rpd.isSignatureProtection() && this.mainSigId != null
                || encryptedTokensIdList.size() > 0 && rmd.isInitiator()) {
            long t3 = 0, t4 = 0;
            if (tlog.isDebugEnabled()) {
                t3 = System.currentTimeMillis();
            }
            log.debug("Signature protection");
            Vector secondEncrParts = new Vector();

            // Now encrypt the signature using the above token
            if (rpd.isSignatureProtection()) {
                secondEncrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
            }

            if (rmd.isInitiator()) {
                for (int i = 0; i < encryptedTokensIdList.size(); i++) {
                    secondEncrParts.add(new WSEncryptionPart((String) encryptedTokensIdList.get(i), "Element"));
                }
            }

            Element secondRefList = null;

            if (encryptionToken.isDerivedKeys()) {
                try {
                    secondRefList = dkEncr.encryptForExternalRef(null, secondEncrParts);
                    RampartUtil.insertSiblingAfter(rmd, encrDKTokenElem, secondRefList);
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInDKEncr");
                }
            } else {
                try {
                    // Encrypt, get hold of the ref list and add it
                    secondRefList = encr.encryptForExternalRef(null, encrParts);
                    RampartUtil.insertSiblingAfter(rmd, encrTokenElement, secondRefList);
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInEncryption", e);
                }
            }
            if (tlog.isDebugEnabled()) {
                t4 = System.currentTimeMillis();
                tlog.debug("Signature protection took :" + (t4 - t3));
            }
        }

    } else {
        throw new RampartException("encryptionTokenMissing");
    }
}

From source file:org.wso2.appcloud.provisioning.runtime.KubernetesRuntimeProvisioningService.java

/**
 * Set runtime properties to kubernetes environment.
 *
 * @param runtimeProperties runtime properties
 * @param deploymentConfig  includes deployment related details
 * @throws RuntimeProvisioningException//  w w w.  j av a 2 s  .c  o m
 */
@Override
public void setRuntimeProperties(List<RuntimeProperty> runtimeProperties, DeploymentConfig deploymentConfig)
        throws RuntimeProvisioningException {

    runtimeProperties.addAll(getRuntimeProperties());

    //list of secretes
    List secrets = new ArrayList();

    //list of env variables
    HashMap<String, String> envVariables = new HashMap<>();

    //create a instance of kubernetes client to invoke service call
    AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient();

    List<VolumeMount> volumeMounts = new ArrayList<>();

    for (RuntimeProperty runtimeProperty : runtimeProperties) {
        switch (runtimeProperty.getPropertyType()) {
        case SENSITIVE:
            if (log.isDebugEnabled()) {
                String message = "Creating property type secret for the application:"
                        + applicationContext.getId() + " for the tenant domain:"
                        + applicationContext.getTenantInfo().getTenantDomain();
                log.debug(message);
            }

            Secret currentSecret = kubernetesClient.secrets().inNamespace(namespace.getMetadata().getName())
                    .withName(runtimeProperty.getName()).get();

            //if secrete exists then replace the same secrete, otherwise create a new secrete
            if (currentSecret != null) {
                kubernetesClient.secrets().inNamespace(namespace.getMetadata().getName())
                        .withName(runtimeProperty.getName()).replace(currentSecret);
            } else {
                Secret secret = new SecretBuilder().withKind(KubernetesPovisioningConstants.KIND_SECRETS)
                        .withNewMetadata().withNamespace(namespace.getMetadata().getName())
                        .withLabels(KubernetesProvisioningUtils.getLableMap(applicationContext))
                        .withName(runtimeProperty.getName()).endMetadata()
                        .withData(runtimeProperty.getProperties()).build();

                kubernetesClient.secrets().create(secret);
            }

            Volume volume = new VolumeBuilder().withName(runtimeProperty.getName()).withNewSecret()
                    .withSecretName(runtimeProperty.getName()).endSecret().build();

            secrets.add(volume);

            //create volume mount for the secretes
            VolumeMount volumeMount = new VolumeMountBuilder().withName(runtimeProperty.getName())
                    .withMountPath(KubernetesPovisioningConstants.VOLUME_MOUNT_PATH + runtimeProperty.getName())
                    .withReadOnly(true).build();

            volumeMounts.add(volumeMount);

            break;
        case ENVIRONMENT:
            if (log.isDebugEnabled()) {
                String message = "Creating property type environment for the application:"
                        + applicationContext.getId() + " for the tenant domain : "
                        + applicationContext.getTenantInfo().getTenantDomain();
                log.debug(message);
            }

            envVariables.putAll(runtimeProperty.getProperties());

            break;
        default:
            String message = "Runtime property type : " + runtimeProperty.getPropertyType() + " not supported.";

            throw new IllegalArgumentException(message);

        }
    }

    //Initially assume first container is the application and set volume mounts
    deploymentConfig.getContainers().get(0).setVolumeMounts(volumeMounts);

    //Set secretes to a pod
    deploymentConfig.setSecrets(secrets);

    //Initially assume first container is the application
    deploymentConfig.getContainers().get(0).setEnvVariables(envVariables);

    //Call deploy application to redeploy application with runtime properties
    deployApplication(deploymentConfig);

}

From source file:com.krawler.spring.crm.leadModule.crmLeadCommonController.java

public ModelAndView storeLead(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    String result = "Problem while submitting your form.";
    HashMap model = new HashMap();
    Map paramMap1 = (java.util.Map) request.getParameterMap();
    HashMap paramMap = new HashMap();
    User user = null;// w  w w.  ja va2  s .c om
    User sender = null;
    // Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
        model.put("successFlag", "1");
        model.put("redirectFlag", "0");
        String successMsg = "Thank you for submitting your information.";
        String val = "";
        int mtyfieldCntr = 0;
        Set arrayKeys = paramMap1.keySet();
        HashMap fieldMap = new HashMap();
        JSONObject fieldJSON = null;
        if (!StringUtil.isNullOrEmpty(request.getParameter("fieldJSON"))) {
            try {
                fieldJSON = new JSONObject(request.getParameter("fieldJSON"));
            } catch (JSONException je) {
                logger.warn("crmLeadCommonController.storeLead :- " + je.getMessage());
            } finally {
                fieldJSON = null;
            }
        }

        HashMap<String, Object> mailFieldsMap = new HashMap<String, Object>();
        HashMap<String, Object> mailValueMap = new HashMap<String, Object>();
        for (Object key : arrayKeys) {
            if (((String) key).startsWith("wl_")) {
                fieldMap.put(key, paramMap1.get((String) key) != null
                        ? new String[] {
                                StringUtil.serverHTMLStripper(((String[]) paramMap1.get((String) key))[0]) }
                        : null);
                if (paramMap1.get((String) key) != null) {
                    val = StringUtil.serverHTMLStripper(((String[]) paramMap1.get((String) key))[0]);
                    if (val.trim().equals("")) {
                        mtyfieldCntr++;
                    }
                }
            }
        }
        if (mtyfieldCntr != fieldMap.size()) {
            paramMap.putAll(paramMap1);
            paramMap.putAll(fieldMap);
            String subdomain = URLUtil.getDomainName(request);
            String companyid = companyDetailsDAOObj.getCompanyid(subdomain);
            Company company = (Company) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.Company",
                    companyid);
            sender = company.getCreator();
            String acceptURL = URLUtil.getRequestPageURL(request, Links.UnprotectedLoginPageFull)
                    + "crm/common/acceptweblead.do";
            int leadRoutingUser = 0;
            CompanyPreferences cmpPref = (CompanyPreferences) kwlCommonTablesDAOObj
                    .getClassObject("com.krawler.crm.database.tables.CompanyPreferences", companyid);
            JSONObject companyPrefObj = crmManagerCommon.getCompanyPreferencesJSON(cmpPref, new JSONObject());
            user = (User) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User",
                    ((String[]) paramMap.get("leadOwner"))[0]);
            if (companyPrefObj.getInt(
                    com.krawler.common.util.Constants.SESSION_LEADROUTING) == LeadRoutingUsers.ROUNDROBIN) {
                user = crmManagerDAOObj.getNextLeadRoutingUsers(companyid).get(0);
                leadRoutingUser = LeadRoutingUsers.ROUNDROBIN;
            }
            if (companyPrefObj
                    .getInt(com.krawler.common.util.Constants.SESSION_LEADROUTING) == LeadRoutingUsers.FCFS) {
                leadRoutingUser = LeadRoutingUsers.FCFS;
            }

            JSONObject resultObj = webtoLeadFormHandlerObj.storeLead(paramMap, companyid, user.getUserID(),
                    acceptURL, leadRoutingUser);

            result = resultObj.optString("msg", result);
            if (!result.equals("Success")) {
                successMsg = result;
                model.put("successFlag", "0");
                txnManager.rollback(status);
            } else {
                CrmLead l = (CrmLead) hibernateTemplate.get(CrmLead.class, resultObj.getString("leadid"));
                if (fieldJSON != null) {
                    Iterator itr = fieldJSON.keys();
                    String keyStr = "";
                    String tmp = "";
                    String str = "";
                    String tmpAr = "";
                    int xtype = 999;
                    String[] valuesArr = null;
                    DefaultMasterItem defItem = null;
                    FieldComboData fieldCombodata = null;
                    Object invoker = null;
                    Class cl = null;
                    CrmLeadCustomData lcdata = null;
                    Method setter = null;
                    List<String> tmpProductlist = new ArrayList<String>();
                    while (itr.hasNext()) {
                        keyStr = (String) itr.next();
                        mailFieldsMap.put(keyStr, fieldJSON.get(keyStr));
                    }

                    for (String tmpStr : mailFieldsMap.keySet()) {
                        if (tmpStr.endsWith("_DROPDOWN#")) {
                            str = tmpStr;
                            str = str.replace("_DROPDOWN#", "");
                            if (tmpStr.startsWith("custom_field")) {
                                str = str.replace("custom_field", "");
                                if (paramMap.get("wl_custom_field" + str) != null) {
                                    fieldCombodata = (FieldComboData) kwlCommonTablesDAOObj.getClassObject(
                                            "com.krawler.common.admin.FieldComboData",
                                            ((String[]) paramMap.get("wl_custom_field" + str))[0]);
                                    if (fieldCombodata == null) { //Custom reference combo check- Since some   custom column may have reference of default combos.
                                        defItem = (DefaultMasterItem) kwlCommonTablesDAOObj.getClassObject(
                                                "com.krawler.crm.database.tables.DefaultMasterItem",
                                                ((String[]) paramMap.get("wl_custom_field" + str))[0]);
                                        if (defItem != null) {
                                            mailValueMap.put(tmpStr, defItem.getValue());
                                        }
                                    } else {
                                        FieldParams fieldParamObj = fieldCombodata.getField();
                                        xtype = fieldParamObj.getFieldtype();
                                        if (xtype == 7) { // for Multi select dropdown
                                            if (request.getParameterValues("wl_custom_field" + str) != null) {
                                                valuesArr = request.getParameterValues("wl_custom_field" + str);
                                                tmp = "";
                                                tmpAr = "";
                                                for (int i = 0; i < valuesArr.length; i++) {
                                                    fieldCombodata = (FieldComboData) kwlCommonTablesDAOObj
                                                            .getClassObject(
                                                                    "com.krawler.common.admin.FieldComboData",
                                                                    valuesArr[i]);
                                                    if (i == valuesArr.length - 1) {
                                                        tmp += fieldCombodata.getValue();
                                                        tmpAr += valuesArr[i];
                                                    } else {
                                                        tmp += fieldCombodata.getValue() + ",";
                                                        tmpAr += valuesArr[i] + ",";
                                                    }
                                                }
                                                mailValueMap.put(tmpStr, tmp);
                                                //Since multiselect combo list has not been saved becoz parammap contains only single value as there are multiple values selected
                                                if (((String[]) paramMap.get(
                                                        "wl_custom_field" + str)).length < valuesArr.length) {
                                                    try {
                                                        lcdata = l.getCrmLeadCustomDataobj();
                                                        cl = Class.forName(
                                                                "com.krawler.crm.database.tables.CrmCustomData");
                                                        invoker = (Object) lcdata;
                                                        setter = cl.getMethod(
                                                                "setCol" + fieldParamObj.getColnum(),
                                                                String.class);
                                                        setter.invoke(invoker, tmpAr);
                                                        l.setCrmLeadCustomDataobj((CrmLeadCustomData) invoker);
                                                    } catch (Exception e) {
                                                        logger.warn(e.getMessage());
                                                    }
                                                }
                                            } else
                                                mailValueMap.put(tmpStr, "");
                                        } else {
                                            fieldCombodata = (FieldComboData) kwlCommonTablesDAOObj
                                                    .getClassObject("com.krawler.common.admin.FieldComboData",
                                                            ((String[]) paramMap
                                                                    .get("wl_custom_field" + str))[0]);
                                            mailValueMap.put(tmpStr, fieldCombodata.getValue());
                                        }
                                    }
                                } else {
                                    mailValueMap.put(tmpStr, "");
                                }
                            } else if (tmpStr.startsWith("productid")) {
                                if (request.getParameterValues("wl_" + str) != null) {
                                    valuesArr = request.getParameterValues("wl_" + str);
                                    tmp = "";
                                    for (int n = 0; n < valuesArr.length; n++) {
                                        if (!tmpProductlist.isEmpty()) {
                                            tmpProductlist.remove(0);
                                        }
                                        tmpProductlist.add(valuesArr[n]);
                                        tmp += ((crmProductDAOObj.getProducts(tmpProductlist)).get(0))
                                                .getProductname() + ",";
                                    }
                                    tmp = tmp.substring(0, tmp.lastIndexOf(','));
                                    mailValueMap.put(tmpStr, tmp);
                                    if (((String[]) paramMap.get("wl_productid")).length < valuesArr.length) {
                                        //Since products list has not been saved becoz parammap contains only single value as there are multiple values selected
                                        try {
                                            crmLeadDAOObj.saveLeadProducts(new String[] { l.getLeadid() },
                                                    valuesArr);
                                        } catch (Exception ex) {
                                            logger.warn(ex.getMessage());
                                        }
                                    }
                                } else
                                    mailValueMap.put(tmpStr, "");
                            } else if (tmpStr.startsWith("type")) {
                                tmp = ((String[]) paramMap.get("wl_" + str))[0];
                                if (tmp == "1")
                                    mailValueMap.put(tmpStr, "Company");
                                else
                                    mailValueMap.put(tmpStr, "Individual");

                            } else {
                                defItem = (DefaultMasterItem) kwlCommonTablesDAOObj.getClassObject(
                                        "com.krawler.crm.database.tables.DefaultMasterItem",
                                        ((String[]) paramMap.get("wl_" + str))[0]);
                                if (defItem != null)
                                    mailValueMap.put(tmpStr, defItem.getValue());
                                else
                                    mailValueMap.put(tmpStr, "");
                            }
                        } else
                            mailValueMap.put(tmpStr,
                                    ((String[]) paramMap.get("wl_" + tmpStr))[0] != null
                                            ? ((String[]) paramMap.get("wl_" + tmpStr))[0]
                                            : "");
                    }
                }
                String id = java.util.UUID.randomUUID().toString();
                String ipaddr = null;
                if (StringUtil.isNullOrEmpty(request.getHeader("x-real-ip"))) {
                    ipaddr = request.getRemoteAddr();
                } else {
                    ipaddr = request.getHeader("x-real-ip");
                }
                auditTrailDAOObj
                        .insertAuditLog(AuditAction.LEAD_CREATE,
                                ((l.getLastname() == null) ? "" : l.getLastname())
                                        + " - Lead created through Web to Lead Form ",
                                ipaddr, user.getUserID(), id);

                crmCommonDAOObj.validaterecorsingledHB(Constants.MODULE_LEAD, l.getLeadid(), companyid);

                txnManager.commit(status);
                if (resultObj.has("leadid")) {
                    String leadid = resultObj.getString("leadid");
                    if (leadRoutingUser == LeadRoutingUsers.ROUNDROBIN) {
                        crmManagerDAOObj.setLastUsedFlagForLeadRouting(user.getUserID(), companyid);
                        if (fieldJSON != null)
                            sendMailToLeadOwner(user, leadid, mailFieldsMap, mailValueMap);
                        else
                            sendMailToLeadOwner(user, leadid, null, null);
                    } else if (leadRoutingUser == LeadRoutingUsers.FCFS) {
                        List<String> recepients = new ArrayList();
                        KwlReturnObject kmsg = crmManagerDAOObj.getAssignedLeadRoutingUsers(companyid,
                                new HashMap<String, Object>());
                        List<User> userlist = kmsg.getEntityList();
                        for (User userObj : userlist) {
                            recepients.add(userObj.getUserID());
                        }
                        Map refTypeMap = new HashMap();
                        Map refIdMap = new HashMap();
                        refIdMap.put("refid1", leadid);
                        refTypeMap.put("reftype1", Constants.Crm_lead_classpath);
                        HashMap<String, Object> extraParams = new HashMap<String, Object>();
                        extraParams.put(NotificationConstants.LOGINURL, acceptURL);
                        if (recepients.size() > 0) {
                            String platformUrl = ConfigReader.getinstance().get("platformURL");
                            if (platformUrl != null) {
                                getPartnerURL(platformUrl, company, CHANNEL.EMAIL, NOTIFICATIONSTATUS.REQUEST,
                                        company.getCreator().getUserID(), recepients, refIdMap, refTypeMap,
                                        extraParams);
                            } else {
                                extraParams.put(NotificationConstants.PARTNERNAME, company.getCompanyName());
                                sendMailToAssignedLeadRoutingUsers(CHANNEL.EMAIL, NOTIFICATIONSTATUS.REQUEST,
                                        company.getCreator().getUserID(), recepients, refIdMap, refTypeMap,
                                        extraParams);
                            }
                        }
                    } else {
                        if (fieldJSON != null)
                            sendMailToLeadOwner(user, leadid, mailFieldsMap, mailValueMap);
                        else
                            sendMailToLeadOwner(user, leadid, null, null);
                    }
                }
            }
            model.put("successMsg", successMsg);
            String returnurl = request.getParameter("returnurl");
            if (!StringUtil.isNullOrEmpty(returnurl)) {
                model.put("redirectFlag", "1");
                model.put("returnurl", returnurl);
            }
        } else {
            model.put("successMsg", "Form should not be empty");
            model.put("successFlag", "0");
            txnManager.rollback(status);
        }

    } catch (Exception e) {
        txnManager.rollback(status);
        logger.warn(e.getMessage(), e);
        if (user != null) {
            sender = user;
        }
        if (sender != null) {
            sendMailToLeadOwner(sender, paramMap1);
        }
    }
    return new ModelAndView("captureLead", "model", model);
}

From source file:org.apache.rampart.builder.SymmetricBindingBuilder.java

private void doSignBeforeEncrypt(RampartMessageData rmd) throws RampartException {

    long t0 = 0, t1 = 0, t2 = 0;

    RampartPolicyData rpd = rmd.getPolicyData();
    Document doc = rmd.getDocument();

    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }// w w  w  .  jav  a 2  s  .c  o m
    Token sigToken = rpd.getSignatureToken();

    String encrTokId = null;
    String sigTokId = null;

    org.apache.rahas.Token encrTok = null;
    org.apache.rahas.Token sigTok = null;
    WSSecKerberosToken krbToken = null;

    Element sigTokElem = null;

    Vector signatureValues = new Vector();

    if (sigToken != null) {
        if (sigToken instanceof SecureConversationToken) {
            sigTokId = rmd.getSecConvTokenId();
        } else if (sigToken instanceof IssuedToken) {
            sigTokId = rmd.getIssuedSignatureTokenId();
        } else if (sigToken instanceof X509Token) {
            if (rmd.isInitiator()) {
                sigTokId = setupEncryptedKey(rmd, sigToken);
            } else {
                sigTokId = getEncryptedKey(rmd);
            }
        } else if (sigToken instanceof KerberosToken) {
            Date created = new Date();
            Date expires = new Date();
            // TODO make this lifetime configurable ???
            expires.setTime(System.currentTimeMillis() + 300000);
            krbToken = getKerberosTokenBuilder(rmd, sigToken);
            sigTokId = krbToken.getBSTTokenId();
            if (rmd.isInitiator()) {
                sigTokElem = krbToken.getBinarySecurityTokenElement();
            }
            sigTok = new EncryptedKeyToken(sigTokId, created, expires);
            sigTok.setSecret(krbToken.getSessionKey().getEncoded());
        }
    } else {
        throw new RampartException("signatureTokenMissing");
    }

    if (sigTokId == null || sigTokId.length() == 0) {
        throw new RampartException("noSecurityToken");
    }

    if (!(sigToken instanceof KerberosToken)) {

        sigTok = this.getToken(rmd, sigTokId);

        if (SPConstants.INCLUDE_TOEKN_ALWAYS == sigToken.getInclusion()
                || SPConstants.INCLUDE_TOKEN_ONCE == sigToken.getInclusion() || (rmd.isInitiator()
                        && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == sigToken.getInclusion())) {
            sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
        } else if ((rmd.isInitiator() && sigToken instanceof X509Token)
                || sigToken instanceof SecureConversationToken) {
            sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
        }
    }

    if (sigTokElem != null) {
        // Set the insertion location
        this.setInsertionLocation(sigTokElem);
    }

    HashMap sigSuppTokMap = null;
    HashMap endSuppTokMap = null;
    HashMap sgndEndSuppTokMap = null;
    HashMap sgndEncSuppTokMap = null;
    HashMap endEncSuppTokMap = null;
    HashMap sgndEndEncSuppTokMap = null;

    Vector sigParts = RampartUtil.getSignedParts(rmd);

    if (this.timestampElement != null) {
        sigParts.add(new WSEncryptionPart(RampartUtil.addWsuIdToElement((OMElement) this.timestampElement)));
    }

    if (rmd.isInitiator()) {
        // Now add the supporting tokens
        SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
        sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);

        SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
        endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);

        SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
        sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);

        SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
        sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);

        SupportingToken endorsingEncryptedSuppTokens = rpd.getEndorsingEncryptedSupportingTokens();
        endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);

        SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();
        sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);

        Vector supportingToks = rpd.getSupportingTokensList();
        for (int i = 0; i < supportingToks.size(); i++) {
            this.handleSupportingTokens(rmd, (SupportingToken) supportingToks.get(i));
        }

        SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
        this.handleSupportingTokens(rmd, encryptedSupportingToks);

        // Setup signature parts
        sigParts = addSignatureParts(sigSuppTokMap, sigParts);
        sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
        sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
        sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);

    } else {
        addSignatureConfirmation(rmd, sigParts);
    }

    if (sigParts.size() > 0) {
        if (sigToken instanceof KerberosToken) {
            krbToken.setParts(sigParts);
            try {
                krbToken.signMessage();
            } catch (WSSecurityException e) {
                throw new RampartException("errorInSignatureWithKerberosToken");
            }
            this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(),
                    krbToken.getSignatureElement()));
            signatureValues.add(krbToken.getSignatureValue());
        } else {
            // Sign the message
            signatureValues.add(this.doSymmSignature(rmd, sigToken, sigTok, sigParts));
        }

        this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) this.getInsertionLocation());

    }

    if (rmd.isInitiator()) {
        // Adding the endorsing encrypted supporting tokens to endorsing supporting tokens
        endSuppTokMap.putAll(endEncSuppTokMap);
        // Do endorsed signatures
        Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);

        for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
            signatureValues.add(iter.next());
        }

        // Adding the signed endorsed encrypted tokens to signed endorsed supporting tokens
        sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
        // Do signed endorsing signatures
        Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
        for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
            signatureValues.add(iter.next());
        }
    }

    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }

    // Encryption
    Token encrToken = rpd.getEncryptionToken();
    boolean isIssuedToken = false;
    if (encrToken instanceof IssuedToken) {
        isIssuedToken = true;
    }
    Element encrTokElem = null;
    if (sigToken.equals(encrToken)) {
        // Use the same token
        encrTokId = sigTokId;
        encrTok = sigTok;
        encrTokElem = sigTokElem;
    } else {
        encrTokId = rmd.getIssuedEncryptionTokenId();
        encrTok = this.getToken(rmd, encrTokId);

        if (SPConstants.INCLUDE_TOEKN_ALWAYS == encrToken.getInclusion()
                || SPConstants.INCLUDE_TOKEN_ONCE == encrToken.getInclusion() || (rmd.isInitiator()
                        && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encrToken.getInclusion())) {
            encrTokElem = (Element) encrTok.getToken();

            // Add the encrToken element before the sigToken element
            RampartUtil.insertSiblingBefore(rmd, sigTokElem, encrTokElem);
        }

    }

    Vector encrParts = RampartUtil.getEncryptedParts(rmd);

    // Check for signature protection
    if (rpd.isSignatureProtection() && this.mainSigId != null) {
        // Now encrypt the signature using the above token
        encrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
    }

    if (rmd.isInitiator()) {
        for (int i = 0; i < encryptedTokensIdList.size(); i++) {
            encrParts.add(new WSEncryptionPart((String) encryptedTokensIdList.get(i), "Element"));
        }
    }

    Element refList = null;
    if (encrParts.size() > 0) {
        // The sec conv token can be used without derived keys
        if (encrToken.isDerivedKeys()) {

            try {
                WSSecDKEncrypt dkEncr = new WSSecDKEncrypt();

                // Check whether it is security policy 1.2 and use the secure conversation
                // accordingly
                if (SPConstants.SP_V12 == encrToken.getVersion()) {
                    dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
                }

                if (encrTokElem != null && encrTok.getAttachedReference() != null) {

                    dkEncr.setExternalKey(encrTok.getSecret(),
                            (Element) doc.importNode((Element) encrTok.getAttachedReference(), true));
                } else if (encrTok.getUnattachedReference() != null) {
                    dkEncr.setExternalKey(encrTok.getSecret(),
                            (Element) doc.importNode((Element) encrTok.getUnattachedReference(), true));
                } else if (!rmd.isInitiator() && encrToken.isDerivedKeys()) {

                    // If the Encrypted key used to create the derived key is not
                    // attached use key identifier as defined in WSS1.1 section
                    // 7.7 Encrypted Key reference
                    SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
                    if (encrTok instanceof EncryptedKeyToken) {
                        tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken) encrTok).getSHA1());
                    }
                    dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());

                } else {
                    dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
                }

                if (encrTok instanceof EncryptedKeyToken) {
                    dkEncr.setCustomValueType(
                            WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE);
                }

                dkEncr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                dkEncr.setDerivedKeyLength(rpd.getAlgorithmSuite().getEncryptionDerivedKeyLength() / 8);
                dkEncr.prepare(doc);
                Element encrDKTokenElem = null;
                encrDKTokenElem = dkEncr.getdktElement();
                if (encrTokElem != null) {
                    RampartUtil.insertSiblingAfter(rmd, encrTokElem, encrDKTokenElem);
                } else if (timestampElement != null) {
                    RampartUtil.insertSiblingAfter(rmd, this.timestampElement, encrDKTokenElem);
                } else {
                    RampartUtil.insertSiblingBefore(rmd, this.getInsertionLocation(), encrDKTokenElem);
                }

                refList = dkEncr.encryptForExternalRef(null, encrParts);

                RampartUtil.insertSiblingAfter(rmd, encrDKTokenElem, refList);

            } catch (WSSecurityException e) {
                throw new RampartException("errorInDKEncr");
            } catch (ConversationException e) {
                throw new RampartException("errorInDKEncr");
            }
        } else {
            try {

                WSSecEncrypt encr = new WSSecEncrypt();

                encr.setWsConfig(rmd.getConfig());
                // Hack to handle reference id issues
                // TODO Need a better fix
                if (encrTokId.startsWith("#")) {
                    encrTokId = encrTokId.substring(1);
                }
                encr.setEncKeyId(encrTokId);

                if (krbToken == null) {
                    encr.setEphemeralKey(encrTok.getSecret());
                    RampartUtil.setEncryptionUser(rmd, encr);
                    encr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                } else {
                    if (encrTok != null) {
                        byte[] secret = encrTok.getSecret();
                        int factor = 0;
                        if (rmd.getPolicyData().getRampartConfig() != null) {
                            KerberosConfig config = null;
                            String fac = null;
                            config = rmd.getPolicyData().getRampartConfig().getKerberosConfig();
                            if ((fac = config.getProp()
                                    .getProperty(KerberosConfig.KDC_DES_AES_FACTOR)) != null) {
                                try {
                                    factor = Integer.parseInt(fac);
                                } catch (Exception e) {
                                    factor = 0;
                                }
                            }
                        }

                        if (factor > 1) {
                            byte[] newSecret = new byte[secret.length * 4];
                            int j = 0;
                            for (int i = 0; i < newSecret.length; i++) {
                                newSecret[i] = secret[j++];
                                if (j == secret.length)
                                    j = 0;
                            }
                            encr.setEphemeralKey(newSecret);
                            encrTok.setSecret(newSecret);
                        } else {
                            encr.setEphemeralKey(secret);
                            encrTok.setSecret(secret);
                        }
                        ((EncryptedKeyToken) encrTok).setSHA1(krbToken.getKrbSession().getThumbPrintEncoded());
                        try {
                            rmd.getTokenStorage().add(sigTok);
                        } catch (TrustException e) {
                            throw new RampartException("errorAddingKerbTokenToStore");
                        }
                    }
                }

                encr.setDocument(doc);
                encr.setEncryptSymmKey(false);

                // Use key identifier in the KeyInfo in server side
                if (!rmd.isInitiator()) {
                    if (krbToken != null) {
                        encr.setUseKeyIdentifier(true);
                        encr.setKeyIdentifierType(WSConstants.KERBEROS_KEY_IDENTIFIER);
                    } else if (encrTok instanceof EncryptedKeyToken) {
                        encr.setUseKeyIdentifier(true);
                        encr.setCustomReferenceValue(((EncryptedKeyToken) encrTok).getSHA1());
                        encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                    } else if (isIssuedToken) {
                        encr.setUseKeyIdentifier(true);
                        encr.setCustomReferenceValue(encrTokId);
                        encr.setKeyIdentifierType(WSConstants.SAML_ASSERTION_IDENTIFIER);
                        try {
                            // RampartUtil.insertSiblingAfter(rmd,this.timestampElement,getLLOMfromOM(encrTok.getToken()));
                        } catch (Exception e) {
                            log.debug("error while converting SAML issued token to a dom element");
                        }
                    }
                }
                encr.prepare(doc,
                        RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(), rmd.getCustomClassLoader()));

                // Encrypt, get hold of the ref list and add it
                refList = encr.encryptForExternalRef(null, encrParts);

                if (encrTokElem != null) {
                    RampartUtil.insertSiblingAfter(rmd, encrTokElem, refList);
                } else {
                    RampartUtil.insertSiblingBeforeOrPrepend(rmd, this.getInsertionLocation(), refList);
                }

            } catch (WSSecurityException e) {
                throw new RampartException("errorInEncryption", e);
            }
        }
    }

    if (tlog.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
        tlog.debug("Signature took :" + (t1 - t0) + ", Encryption took :" + (t2 - t1));
    }

}