Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:org.kuali.ole.select.document.service.impl.OleCreditMemoServiceImpl.java

/**
 * @see org.kuali.ole.module.purap.document.service.CreditMemoCreateService# populateDocumentAfterInit(org.kuali.ole.module.purap.document.CreditMemoDocument)
 *//*from w w w.j  a v a2s .c  o m*/
@Override
public void populateDocumentAfterInit(VendorCreditMemoDocument cmDocument) {

    OleVendorCreditMemoDocument vendorCreditMemoDocument = (OleVendorCreditMemoDocument) cmDocument;
    // make a call to search for expired/closed accounts
    HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList = accountsPayableService
            .getExpiredOrClosedAccountList(cmDocument);

    if (vendorCreditMemoDocument.isSourceDocumentPaymentRequest()
            && vendorCreditMemoDocument.getInvoiceIdentifier() == null) {
        populateDocumentFromPreq(vendorCreditMemoDocument, expiredOrClosedAccountList);
    } else if (vendorCreditMemoDocument.isSourceDocumentPurchaseOrder()
            && vendorCreditMemoDocument.getInvoiceIdentifier() == null) {
        populateDocumentFromPO(vendorCreditMemoDocument, expiredOrClosedAccountList);
    } else if (vendorCreditMemoDocument.getInvoiceIdentifier() != null) {
        populateDocumentFromInvoice(vendorCreditMemoDocument, expiredOrClosedAccountList);
    } else {
        populateDocumentFromVendor(vendorCreditMemoDocument);
    }

    populateDocumentDescription(vendorCreditMemoDocument);

    // write a note for expired/closed accounts if any exist and add a message stating there were expired/closed accounts at the
    // top of the document
    accountsPayableService.generateExpiredOrClosedAccountNote(cmDocument, expiredOrClosedAccountList);

    // set indicator so a message is displayed for accounts that were replaced due to expired/closed status
    if (ObjectUtils.isNotNull(expiredOrClosedAccountList) && !expiredOrClosedAccountList.isEmpty()) {
        cmDocument.setContinuationAccountIndicator(true);
    }

}

From source file:org.eurekastreams.server.persistence.mappers.db.UpdatePersonMapper.java

/**
 * Update the person in the DB./*from  w w  w .  j a v a  2 s .c om*/
 * 
 * @param ldapPerson
 *            {@link Person}.
 * @return {@link UpdatePersonResponse}.
 */
@Override
public UpdatePersonResponse execute(final Person ldapPerson) {
    Person dbPerson = (Person) getEntityManager().createQuery("FROM Person where accountId = :accountId")
            .setParameter("accountId", ldapPerson.getAccountId()).getSingleResult();

    HashMap<String, String> ldapAdditionalProperties = ldapPerson.getAdditionalProperties();
    HashMap<String, String> dbAdditionalProperties = dbPerson.getAdditionalProperties();
    boolean wasPersonUpdated = false;
    boolean wasPersonDisplayNameUpdated = false;

    // Checks to see if last name in ldap matches what the db has, updating db if they don't match.
    if (!dbPerson.getLastName().equals(ldapPerson.getLastName())) {
        dbPerson.setLastName(ldapPerson.getLastName());
        wasPersonUpdated = true;
        wasPersonDisplayNameUpdated = true;
    }

    // Checks to see if company in ldap matches what the db has, updating db if they don't match.
    if ((dbPerson.getCompanyName() == null && ldapPerson.getCompanyName() != null)
            || (dbPerson.getCompanyName() != null
                    // line wrap
                    && !dbPerson.getCompanyName().equals(ldapPerson.getCompanyName()))) {
        dbPerson.setCompanyName(ldapPerson.getCompanyName());
        wasPersonUpdated = true;
    }

    // Checks to see if the display name suffix has changed - (displayNameSuffix isn't nullable)
    log.debug("Checking if the displayNameSuffix changed");
    String newDisplayNameSuffix = "";
    if (ldapPerson.getDisplayNameSuffix() != null) {
        newDisplayNameSuffix = ldapPerson.getDisplayNameSuffix();
    }
    if (!dbPerson.getDisplayNameSuffix().equals(newDisplayNameSuffix)) {
        // display name has changed
        log.debug("displayNameSuffix did change - new value: " + newDisplayNameSuffix);
        dbPerson.setDisplayNameSuffix(newDisplayNameSuffix);
        wasPersonUpdated = true;
        wasPersonDisplayNameUpdated = true;
    }

    // Looks for any additional properties defined for the person retrieved from ldap call.
    if (ldapAdditionalProperties != null && !ldapAdditionalProperties.isEmpty()) {
        boolean changed = false;
        if (dbAdditionalProperties == null) {
            changed = true;
        } else {
            // determine if properties are different
            // first check for new or changed values
            for (String key : ldapAdditionalProperties.keySet()) {
                String value = ldapAdditionalProperties.get(key);
                if (!value.equalsIgnoreCase(dbAdditionalProperties.get(key))) {
                    changed = true;
                    break;
                }
            }
            // then check for deleted values
            if (!changed) {
                for (String key : dbAdditionalProperties.keySet()) {
                    if (!ldapAdditionalProperties.containsKey(key)) {
                        changed = true;
                        break;
                    }
                }
            }
        }

        // Updates the db user, if necessary.
        if (changed) {
            dbPerson.setAdditionalProperties(ldapAdditionalProperties);
            wasPersonUpdated = true;
        }
    }
    // Finds if any previously set db properties are no longer necessary due to not being defined on ldap person.
    else if (dbAdditionalProperties != null) {
        dbPerson.setAdditionalProperties(null);
        wasPersonUpdated = true;
    }

    if (wasPersonUpdated) {
        getEntityManager().flush();
    }

    return new UpdatePersonResponse(dbPerson.getId(), wasPersonUpdated, wasPersonDisplayNameUpdated);
}

From source file:org.apache.tika.parser.ner.NLTKNERecogniserTest.java

@Test
public void testGetEntityTypes() throws Exception {
    System.setProperty(NamedEntityParser.SYS_PROP_NER_IMPL, NLTKNERecogniser.class.getName());
    Tika tika = new Tika(new TikaConfig(NamedEntityParser.class.getResourceAsStream("tika-config.xml")));

    JSONParser parser = new JSONParser();
    String text = "";

    HashMap<Integer, String> hmap = new HashMap<Integer, String>();
    HashMap<String, HashMap<Integer, String>> outerhmap = new HashMap<String, HashMap<Integer, String>>();

    int index = 0;
    //Input Directory Path
    String inputDirPath = "/Users/AravindMac/Desktop/polardata_json_grobid/application_pdf";
    int count = 0;

    try {/*from  w  w w  .j a  v a 2s  . c om*/

        File root = new File(inputDirPath);
        File[] listDir = root.listFiles();
        for (File filename : listDir) {

            if (!filename.getName().equals(".DS_Store") && count < 3239) {
                count += 1;
                System.out.println(count);

                String absoluteFilename = filename.getAbsolutePath().toString();

                //   System.out.println(absoluteFilename);
                //Read the json file, parse and retrieve the text present in the content field.

                Object obj = parser.parse(new FileReader(absoluteFilename));

                BufferedWriter bw = new BufferedWriter(new FileWriter(new File(absoluteFilename)));

                JSONObject jsonObject = (JSONObject) obj;
                text = (String) jsonObject.get("content");

                Metadata md = new Metadata();
                tika.parse(new ByteArrayInputStream(text.getBytes()), md);

                //Parse the content and retrieve the values tagged as the NER entities
                HashSet<String> set = new HashSet<String>();

                // Store values tagged as NER_NAMES
                set.addAll(Arrays.asList(md.getValues("NER_NAMES")));

                hmap = new HashMap<Integer, String>();
                index = 0;

                for (Iterator<String> i = set.iterator(); i.hasNext();) {
                    String f = i.next();
                    hmap.put(index, f);
                    index++;
                }

                if (!hmap.isEmpty()) {
                    outerhmap.put("NAMES", hmap);
                }

                JSONArray array = new JSONArray();
                array.put(outerhmap);

                if (!outerhmap.isEmpty()) {
                    jsonObject.put("NLTK", array); //Add the NER entities to the json under NER key as a JSON array.
                }

                System.out.println(jsonObject);

                bw.write(jsonObject.toJSONString()); //Stringify thr JSON and write it back to the file 
                bw.close();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.h3xstream.findsecbugs.crypto.InsecureSmtpSslDetector.java

private void analyzeMethod(Method m, ClassContext classContext)
        throws CFGBuilderException, DataflowAnalysisException {

    HashMap<Location, String> sslConnMap = new HashMap<Location, String>();
    HashSet<String> sslCertVerSet = new HashSet<String>();
    Location locationWeakness = null;
    String hostName = null;//from w  ww . j  a  v a 2  s. co m

    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    CFG cfg = classContext.getCFG(m);

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();

        Instruction inst = location.getHandle().getInstruction();

        if (inst instanceof INVOKEVIRTUAL) {
            INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst;
            if (INSECURE_APIS.contains(invoke.getClassName(cpg))
                    && "setHostName".equals(invoke.getMethodName(cpg))) {
                hostName = ByteCode.getConstantLDC(location.getHandle().getPrev(), cpg, String.class);
            }
            if (INSECURE_APIS.contains(invoke.getClassName(cpg))
                    && "setSSLOnConnect".equals(invoke.getMethodName(cpg))) {
                Integer sslOn = ByteCode.getConstantInt(location.getHandle().getPrev());
                if (sslOn != null && sslOn == 1) {
                    sslConnMap.put(location, invoke.getClassName(cpg) + hostName);
                }
            }
            if (INSECURE_APIS.contains(invoke.getClassName(cpg))
                    && "setSSLCheckServerIdentity".equals(invoke.getMethodName(cpg))) {
                Integer checkOn = ByteCode.getConstantInt(location.getHandle().getPrev());
                if (checkOn != null && checkOn == 1) {
                    sslCertVerSet.add(invoke.getClassName(cpg) + hostName);
                }
            }
        }
    }

    //Both conditions - setSSLOnConnect and setSSLCheckServerIdentity
    //haven't been found in the same instance (verifing instance by class name + host name)
    sslConnMap.values().removeAll(sslCertVerSet);

    if (!sslConnMap.isEmpty()) {
        for (Location key : sslConnMap.keySet()) {
            JavaClass clz = classContext.getJavaClass();
            bugReporter.reportBug(new BugInstance(this, INSECURE_SMTP_SSL, Priorities.HIGH_PRIORITY)
                    .addClass(clz).addMethod(clz, m).addSourceLine(classContext, m, key));
        }
    }
}

From source file:org.opensilk.music.library.mediastore.util.FilesUtil.java

@NonNull
public static List<Track> convertAudioFilesToTracks(Context context, File base, List<File> audioFiles) {
    if (audioFiles.size() == 0) {
        return Collections.emptyList();
    }//w  w w .j a v  a2s. co m

    final List<Track> trackList = new ArrayList<>(audioFiles.size());

    Cursor c = null;
    try {
        final HashMap<String, File> pathMap = new HashMap<>();

        //Build the selection
        final int size = audioFiles.size();
        final StringBuilder selection = new StringBuilder();
        selection.append(MediaStore.Audio.AudioColumns.DATA + " IN (");
        for (int i = 0; i < size; i++) {
            final File f = audioFiles.get(i);
            final String path = f.getAbsolutePath();
            pathMap.put(path, f); //Add file to map while where iterating
            //TODO it would probably be better to use selectionArgs
            selection.append("'").append(StringUtils.replace(path, "'", "''")).append("'");
            if (i < size - 1) {
                selection.append(",");
            }
        }
        selection.append(")");

        //make query
        c = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                Projections.SONG_FILE, selection.toString(), null, null);
        if (c != null && c.moveToFirst()) {
            do {
                final File f = pathMap
                        .remove(c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)));
                if (f != null) {
                    try {
                        Track.Builder tb = Track.builder()
                                .setIdentity(c.getString(c.getColumnIndexOrThrow(BaseColumns._ID)))
                                .setName(getStringOrNull(c, MediaStore.Audio.AudioColumns.DISPLAY_NAME))
                                .setArtistName(getStringOrNull(c, MediaStore.Audio.AudioColumns.ARTIST))
                                .setAlbumName(getStringOrNull(c, MediaStore.Audio.AudioColumns.ALBUM))
                                .setAlbumArtistName(getStringOrNull(c, "album_artist"))
                                .setAlbumIdentity(getStringOrNull(c, MediaStore.Audio.AudioColumns.ALBUM_ID))
                                .setDuration(
                                        (int) (getLongOrZero(c, MediaStore.Audio.AudioColumns.DURATION) / 1000))
                                .setMimeType(getStringOrNull(c, MediaStore.Audio.AudioColumns.MIME_TYPE))
                                .setDataUri(
                                        generateDataUri(c.getString(c.getColumnIndexOrThrow(BaseColumns._ID))))
                                .setArtworkUri(generateArtworkUri(
                                        c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID))));
                        trackList.add(tb.build());
                    } catch (IllegalArgumentException ignored) {
                    }
                }
            } while (c.moveToNext());
        }
        if (!pathMap.isEmpty()) {
            Timber.w("%d audioFiles didn't make the cursor", pathMap.size());
            for (File f : pathMap.values()) {
                trackList.add(makeTrackFromFile(base, f));
            }
        }
    } catch (Exception e) {
        if (DUMPSTACKS)
            Timber.e(e, "convertAudioFilesToTracks");
    } finally {
        closeQuietly(c);
    }
    return trackList;
}

From source file:org.akaza.openclinica.control.submit.CreateOneDiscrepancyNoteServlet.java

@Override
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());

    int eventCRFId = fp.getInt(CreateDiscrepancyNoteServlet.EVENT_CRF_ID);
    request.setAttribute(CreateDiscrepancyNoteServlet.EVENT_CRF_ID, new Integer(eventCRFId));

    int parentId = fp.getInt(PARENT_ID);
    DiscrepancyNoteBean parent = parentId > 0 ? (DiscrepancyNoteBean) dndao.findByPK(parentId)
            : new DiscrepancyNoteBean();
    HashMap<Integer, DiscrepancyNoteBean> boxDNMap = (HashMap<Integer, DiscrepancyNoteBean>) session
            .getAttribute(BOX_DN_MAP);//  ww  w .j a  v a2  s .  co m
    boxDNMap = boxDNMap == null ? new HashMap<Integer, DiscrepancyNoteBean>() : boxDNMap;
    DiscrepancyNoteBean dn = boxDNMap.size() > 0 && boxDNMap.containsKey(Integer.valueOf(parentId))
            ? boxDNMap.get(Integer.valueOf(parentId))
            : new DiscrepancyNoteBean();
    int entityId = fp.getInt(ENTITY_ID, true);
    entityId = entityId > 0 ? entityId : parent.getEntityId();
    if (entityId == 0) {
        Validator.addError(errors, "newChildAdded" + parentId, respage.getString("note_cannot_be_saved"));
        logger.info("entityId is 0. Note saving can not be started.");
    }
    String entityType = fp.getString(ENTITY_TYPE, true);

    FormDiscrepancyNotes noteTree = (FormDiscrepancyNotes) session
            .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    if (noteTree == null) {
        noteTree = new FormDiscrepancyNotes();
    }
    String ypos = fp.getString("ypos" + parentId);
    int refresh = 0;
    String field = fp.getString(ENTITY_FIELD, true);

    //String description = fp.getString("description" + parentId);
    int typeId = fp.getInt("typeId" + parentId);
    String detailedDes = fp.getString("detailedDes" + parentId);
    int resStatusId = fp.getInt(RES_STATUS_ID + parentId);
    int assignedUserAccountId = fp.getInt(SUBMITTED_USER_ACCOUNT_ID + parentId);
    String viewNoteLink = fp.getString("viewDNLink" + parentId);
    viewNoteLink = this.appendPageFileName(viewNoteLink, "fromBox", "1");

    Validator v = new Validator(request);
    v.addValidation("detailedDes" + parentId, Validator.NO_BLANKS);
    // v.addValidation("description" + parentId, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
    v.addValidation("detailedDes" + parentId, Validator.LENGTH_NUMERIC_COMPARISON,
            NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 1000);
    v.addValidation("typeId" + parentId, Validator.NO_BLANKS);
    HashMap errors = v.validate();

    dn.setParentDnId(parentId);
    // dn.setDescription(description);
    dn.setDiscrepancyNoteTypeId(typeId);
    dn.setDetailedNotes(detailedDes);
    dn.setResolutionStatusId(resStatusId);
    if (typeId != DiscrepancyNoteType.ANNOTATION.getId()
            && typeId != DiscrepancyNoteType.REASON_FOR_CHANGE.getId()) {
        dn.setAssignedUserId(assignedUserAccountId);
    }
    if (DiscrepancyNoteType.ANNOTATION.getId() == dn.getDiscrepancyNoteTypeId()) {
        updateStudyEvent(entityType, entityId);
        updateStudySubjectStatus(entityType, entityId);
    }
    if (DiscrepancyNoteType.ANNOTATION.getId() == dn.getDiscrepancyNoteTypeId()
            || DiscrepancyNoteType.REASON_FOR_CHANGE.getId() == dn.getDiscrepancyNoteTypeId()) {
        dn.setResStatus(ResolutionStatus.NOT_APPLICABLE);
        dn.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId());
    }
    if (DiscrepancyNoteType.FAILEDVAL.getId() == dn.getDiscrepancyNoteTypeId()
            || DiscrepancyNoteType.QUERY.getId() == dn.getDiscrepancyNoteTypeId()) {
        if (ResolutionStatus.NOT_APPLICABLE.getId() == dn.getResolutionStatusId()) {
            Validator.addError(errors, RES_STATUS_ID + parentId, restext.getString("not_valid_res_status"));
        }
    }
    //

    if (errors.isEmpty()) {
        HashMap<String, ArrayList<String>> results = new HashMap<String, ArrayList<String>>();
        ArrayList<String> mess = new ArrayList<String>();

        String column = fp.getString(ENTITY_COLUMN, true);

        dn.setOwner(ub);
        dn.setStudyId(currentStudy.getId());
        dn.setEntityId(entityId);
        dn.setEntityType(entityType);
        dn.setColumn(column);
        dn.setField(field);

        if (parentId > 0) {
            if (dn.getResolutionStatusId() != parent.getResolutionStatusId()) {
                parent.setResolutionStatusId(dn.getResolutionStatusId());
                dndao.update(parent);
                if (!parent.isActive()) {
                    logger.info(
                            "Failed to update resolution status ID for the parent dn ID = " + parentId + ". ");
                }
            }
            if (dn.getAssignedUserId() != parent.getAssignedUserId()) {
                parent.setAssignedUserId(dn.getAssignedUserId());
                if (parent.getAssignedUserId() > 0) {
                    dndao.updateAssignedUser(parent);
                } else {
                    dndao.updateAssignedUserToNull(parent);
                }
                if (!parent.isActive()) {
                    logger.info("Failed to update assigned user ID for the parent dn ID= " + parentId + ". ");
                }
            }
        } else {
            ypos = "0";
        }

        dn = (DiscrepancyNoteBean) dndao.create(dn);
        boolean success = dn.getId() > 0 ? true : false;
        if (success) {
            refresh = 1;
            dndao.createMapping(dn);
            success = dndao.isQuerySuccessful();
            if (success == false) {
                mess.add(restext.getString("failed_create_dn_mapping_for_dnId") + dn.getId() + ". ");
            }

            noteTree.addNote(eventCRFId + "_" + field, dn);
            noteTree.addIdNote(dn.getEntityId(), field);
            session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, noteTree);
            if (dn.getParentDnId() == 0) {
                // see issue 2659 this is a new thread, we will create
                // two notes in this case,
                // This way one can be the parent that updates as the
                // status changes, but one also stays as New.
                dn.setParentDnId(dn.getId());
                dn = (DiscrepancyNoteBean) dndao.create(dn);
                if (dn.getId() > 0) {
                    dndao.createMapping(dn);
                    if (!dndao.isQuerySuccessful()) {
                        mess.add(restext.getString("failed_create_dn_mapping_for_dnId") + dn.getId() + ". ");
                    }
                    noteTree.addNote(eventCRFId + "_" + field, dn);
                    noteTree.addIdNote(dn.getEntityId(), field);
                    session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, noteTree);
                } else {
                    mess.add(restext.getString("failed_create_child_dn_for_new_parent_dnId") + dn.getId()
                            + ". ");
                }
            }
        } else {
            mess.add(restext.getString("failed_create_new_dn") + ". ");
        }

        if (success) {
            if (boxDNMap.size() > 0 && boxDNMap.containsKey(parentId)) {
                boxDNMap.remove(parentId);
            }
            session.removeAttribute(BOX_TO_SHOW);
            /*
             * Copied from CreateDiscrepancyNoteServlet
             * Setting a marker to check
             * later while saving administrative edited data. This is needed to
             * make sure the system flags error while changing data for items
             * which already has a DiscrepanyNote
             */
            manageReasonForChangeState(session, eventCRFId + "_" + field);
            String email = fp.getString(EMAIL_USER_ACCOUNT + parentId);
            if (dn.getAssignedUserId() > 0 && "1".equals(email.trim())) {
                logger.info("++++++ found our way here");
                // generate email for user here
                StringBuffer message = new StringBuffer();

                dn = getNoteInfo(dn);

                // generate message here
                EmailEngine em = new EmailEngine(EmailEngine.getSMTPHost());
                UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource());
                ItemDAO itemDAO = new ItemDAO(sm.getDataSource());
                ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
                ItemBean item = new ItemBean();
                ItemDataBean itemData = new ItemDataBean();

                StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
                UserAccountBean assignedUser = (UserAccountBean) userAccountDAO
                        .findByPK(dn.getAssignedUserId());
                String alertEmail = assignedUser.getEmail();
                message.append(MessageFormat.format(respage.getString("mailDNHeader"),
                        assignedUser.getFirstName(), assignedUser.getLastName()));
                message.append("<A HREF='" + SQLInitServlet.getField("sysURL.base")
                        + "ViewNotes?module=submit&listNotes_f_discrepancyNoteBean.user="
                        + assignedUser.getName() + "&listNotes_f_entityName=" + dn.getEntityName() + "'>"
                        + SQLInitServlet.getField("sysURL.base") + "</A><BR/>");
                message.append(respage.getString("you_received_this_from"));
                StudyBean study = (StudyBean) studyDAO.findByPK(dn.getStudyId());

                if ("itemData".equalsIgnoreCase(entityType)) {
                    itemData = (ItemDataBean) iddao.findByPK(dn.getEntityId());
                    item = (ItemBean) itemDAO.findByPK(itemData.getItemId());
                }

                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("disc_note_info"));
                message.append(respage.getString("email_body_separator"));
                message.append(MessageFormat.format(respage.getString("mailDNParameters1"),
                        dn.getDetailedNotes(), ub.getName()));
                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("entity_information"));
                message.append(respage.getString("email_body_separator"));
                message.append(MessageFormat.format(respage.getString("mailDNParameters2"), study.getName(),
                        dn.getSubjectName()));

                if (!("studySub".equalsIgnoreCase(entityType) || "subject".equalsIgnoreCase(entityType))) {
                    message.append(
                            MessageFormat.format(respage.getString("mailDNParameters3"), dn.getEventName()));
                    if (!"studyEvent".equalsIgnoreCase(dn.getEntityType())) {
                        message.append(
                                MessageFormat.format(respage.getString("mailDNParameters4"), dn.getCrfName()));
                        if (!"eventCrf".equalsIgnoreCase(dn.getEntityType())) {
                            message.append(MessageFormat.format(respage.getString("mailDNParameters6"),
                                    item.getName()));
                        }
                    }
                }

                message.append(respage.getString("email_body_separator"));
                message.append(MessageFormat.format(respage.getString("mailDNThanks"), study.getName()));
                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("disclaimer"));
                message.append(respage.getString("email_body_separator"));
                message.append(respage.getString("email_footer"));

                /*
                 *
                 *
                 *
                 * Please select the link below to view the information
                 * provided. You may need to login to
                 * OpenClinica_testbed with your user name and password
                 * after selecting the link. If you receive a page
                 * cannot be displayed message, please make sure to
                 * select the Change Study/Site link in the upper right
                 * table of the page, select the study referenced above,
                 * and select the link again.
                 *
                 * https://openclinica.s-3.com/OpenClinica_testbed/
                 * ViewSectionDataEntry ?ecId=117&sectionId=142&tabId=2
                 */

                String emailBodyString = message.toString();
                String entityName = getEntityName(dn);
                sendEmail(alertEmail.trim(), EmailEngine.getAdminEmail(),
                        MessageFormat.format(respage.getString("mailDNSubject"), study.getName(), entityName),
                        emailBodyString, true, null, null, true);
            }

            String close = fp.getString("close" + parentId);
            //session.setAttribute(CLOSE_WINDOW, "true".equals(close)?"true":"");
            if ("true".equals(close)) {
                addPageMessage(respage.getString("note_saved_into_db"));
                addPageMessage(respage.getString("page_close_automatically"));
                forwardPage(Page.ADD_DISCREPANCY_NOTE_SAVE_DONE);
                logger.info("Should forwardPage to ADD_DISCREPANCY_NOTE_SAVE_DONE.");
            } else {
                if (parentId == dn.getParentDnId()) {
                    mess.add(restext.getString("a_new_child_dn_added"));
                    results.put("newChildAdded" + parentId, mess);
                    setInputMessages(results);
                } else {
                    addPageMessage(restext.getString("a_new_dn_thread_added"));
                }
            }

        } else {
            session.setAttribute(BOX_TO_SHOW, parentId + "");
        }

    } else {
        setInputMessages(errors);
        boxDNMap.put(Integer.valueOf(parentId), dn);
        session.setAttribute(BOX_TO_SHOW, parentId + "");
    }
    session.setAttribute(BOX_DN_MAP, boxDNMap);
    viewNoteLink = this.appendPageFileName(viewNoteLink, "refresh", refresh + "");
    viewNoteLink = this.appendPageFileName(viewNoteLink, "y", ypos != null && ypos.length() > 0 ? ypos : "0");

    getServletContext().getRequestDispatcher(viewNoteLink).forward(request, response);
    // forwardPage(Page.setNewPage(viewNoteLink, Page.VIEW_DISCREPANCY_NOTE.getTitle()));

}

From source file:com.wasteofplastic.acidisland.commands.Challenges.java

private boolean giveItems(Player player, String[] itemRewards) {
    Material rewardItem;//from   ww  w .  j  av a2 s. c  om
    int rewardQty;
    // Build the item stack of rewards to give the player
    for (final String s : itemRewards) {
        final String[] element = s.split(":");
        if (element.length == 2) {
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[1]);
                final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                        .addItem(new ItemStack[] { new ItemStack(rewardItem, rewardQty) });
                if (!leftOvers.isEmpty()) {
                    player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                }
                player.getWorld().playSound(player.getLocation(), Sound.ITEM_PICKUP, 1F, 1F);
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorRewardProblem);
                plugin.getLogger().severe("Could not give " + element[0] + ":" + element[1] + " to "
                        + player.getName() + " for challenge reward!");
                String materialList = "";
                boolean hint = false;
                for (Material m : Material.values()) {
                    materialList += m.toString() + ",";
                    if (element[0].length() > 3) {
                        if (m.toString().startsWith(element[0].substring(0, 3))) {
                            plugin.getLogger().severe(
                                    "Did you mean " + m.toString() + "? If so, put that in challenges.yml.");
                            hint = true;
                        }
                    }
                }
                if (!hint) {
                    plugin.getLogger().severe(
                            "Sorry, I have no idea what " + element[0] + " is. Pick from one of these:");
                    plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                }
            }
        } else if (element.length == 3) {
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[2]);
                // Check for POTION
                if (rewardItem.equals(Material.POTION)) {
                    // Add the effect of the potion
                    final PotionEffectType potionType = PotionEffectType.getByName(element[1]);
                    if (potionType == null) {
                        plugin.getLogger().severe(
                                "Reward potion effect type in config.yml challenges is unknown - skipping!");
                    } else {
                        final Potion rewPotion = new Potion(PotionType.getByEffect(potionType));
                        final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                                .addItem(new ItemStack[] { rewPotion.toItemStack(rewardQty) });
                        if (!leftOvers.isEmpty()) {
                            player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                        }
                    }
                } else {
                    // Normal item, not a potion
                    int rewMod = Integer.parseInt(element[1]);
                    final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                            .addItem(new ItemStack[] { new ItemStack(rewardItem, rewardQty, (short) rewMod) });
                    if (!leftOvers.isEmpty()) {
                        player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                    }
                }
                player.getWorld().playSound(player.getLocation(), Sound.ITEM_PICKUP, 1F, 1F);
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + "There was a problem giving your reward. Ask Admin to check log!");
                plugin.getLogger().severe("Could not give " + element[0] + ":" + element[1] + " to "
                        + player.getName() + " for challenge reward!");
                if (element[0].equalsIgnoreCase("POTION")) {
                    String potionList = "";
                    boolean hint = false;
                    for (PotionEffectType m : PotionEffectType.values()) {
                        potionList += m.toString() + ",";
                        if (element[1].length() > 3) {
                            if (m.toString().startsWith(element[1].substring(0, 3))) {
                                plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                                hint = true;
                            }
                        }
                    }
                    if (!hint) {
                        plugin.getLogger().severe("Sorry, I have no idea what potion type " + element[1]
                                + " is. Pick from one of these:");
                        plugin.getLogger().severe(potionList.substring(0, potionList.length() - 1));
                    }
                } else {
                    String materialList = "";
                    boolean hint = false;
                    for (Material m : Material.values()) {
                        materialList += m.toString() + ",";
                        if (m.toString().startsWith(element[0].substring(0, 3))) {
                            plugin.getLogger().severe(
                                    "Did you mean " + m.toString() + "? If so, put that in challenges.yml.");
                            hint = true;
                        }
                    }
                    if (!hint) {
                        plugin.getLogger().severe(
                                "Sorry, I have no idea what " + element[0] + " is. Pick from one of these:");
                        plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                    }
                }
                return false;
            }
        } else if (element.length == 6) {
            //plugin.getLogger().info("DEBUG: 6 element reward");
            // Potion format = POTION:name:level:extended:splash:qty
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[5]);
                // Check for POTION
                if (rewardItem.equals(Material.POTION)) {
                    // Add the effect of the potion
                    final PotionType potionType = PotionType.valueOf(element[1]);
                    if (potionType == null) {
                        plugin.getLogger().severe(
                                "Reward potion effect type in config.yml challenges is unknown - skipping!");
                    } else {
                        final Potion rewPotion = new Potion(potionType);
                        // Add extended, splash, level etc.
                        rewPotion.setLevel(Integer.valueOf(element[2]));
                        //plugin.getLogger().info("DEBUG: level = " + Integer.valueOf(element[2]));
                        if (element[3].equalsIgnoreCase("EXTENDED")) {
                            //plugin.getLogger().info("DEBUG: Extended");
                            if (potionType != PotionType.INSTANT_DAMAGE
                                    && potionType != PotionType.INSTANT_HEAL) {
                                // Instant potions cannot be extended
                                rewPotion.setHasExtendedDuration(true);
                            } else {
                                plugin.getLogger()
                                        .warning("Reward potion is an instant potion and cannot be extended!");
                            }
                        }
                        if (element[4].equalsIgnoreCase("SPLASH")) {
                            //plugin.getLogger().info("DEBUG: splash");
                            rewPotion.setSplash(true);
                        }
                        //plugin.getLogger().info("DEBUG: adding items!");
                        final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                                .addItem(new ItemStack[] { rewPotion.toItemStack(rewardQty) });
                        if (!leftOvers.isEmpty()) {
                            player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                        }
                    }
                }
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + "There was a problem giving your reward. Ask Admin to check log!");
                plugin.getLogger().severe("Problem with reward potion: " + s);
                plugin.getLogger()
                        .severe("Format POTION:NAME:<LEVEL>:<EXTENDED/NOTEXTENDED>:<SPLASH/NOSPLASH>:QTY");
                plugin.getLogger().severe("LEVEL, EXTENDED and SPLASH are optional");
                plugin.getLogger().severe("LEVEL is a number");
                plugin.getLogger().severe("Examples:");
                plugin.getLogger().severe("POTION:STRENGTH:1:EXTENDED:SPLASH:1");
                plugin.getLogger().severe("POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1");
                plugin.getLogger().severe("POTION:WEAKNESS::::1   -  any weakness potion");
                plugin.getLogger().severe("Available names are:");
                String potionNames = "";
                for (PotionType p : PotionType.values()) {
                    potionNames += p.toString() + ", ";
                }
                plugin.getLogger().severe(potionNames.substring(0, potionNames.length() - 2));
                return false;
            }
        }
    }
    return true;
}

From source file:com.clustercontrol.jobmanagement.factory.CreateJobSession.java

/**
 * ?????//w  ww  . j  ava  2 s . c o m
 * <p>
 * <ol>
 * <li>????</li>
 * <li>????</li>
 * <li>????</li>
 * <li>??????</li>
 * <li>????</li>
 * </ol>
 *
 * @param job ??
 * @param sessionId ID
 * @return
 * @throws JobInfoNotFound
 * @throws FacilityNotFound
 * @throws EntityExistsException
 * @throws HinemosUnknown
 * @throws JobMasterNotFound
 * @throws InvalidRole
 * @throws RoleNotFound 
 */
public static JobSessionJobEntityPK createJobSessionJob(JobMstEntity job, String sessionId,
        OutputBasicInfo info, boolean first, JobTriggerInfo triggerInfo, JobMstEntity referJob,
        HashMap<String, String> jobIdMap) throws JobInfoNotFound, FacilityNotFound, EntityExistsException,
        HinemosUnknown, JobMasterNotFound, InvalidRole, RoleNotFound {

    m_log.debug("createJobSessionJob() sessionId=" + sessionId + " first=" + first);

    JpaTransactionManager jtm = new JpaTransactionManager();
    HinemosEntityManager em = jtm.getEntityManager();

    String jobunitId = job.getId().getJobunitId();
    String jobId = job.getId().getJobId();

    //JobSessionEntity
    JobSessionEntity jobSessionEntity = em.find(JobSessionEntity.class, sessionId, ObjectPrivilegeMode.READ);
    //
    JobSessionJobEntity parentJobSessionJobEntity = null;

    String parentJobunitId = job.getParentJobunitId();
    String parentJobId = job.getParentJobId();
    //?????????ID?????
    //???ID????(ID????ID???????)
    //???????(?)?ID(?)???????referJobnull?
    //(??????????????referJob????????????)
    if (referJob != null) {
        m_log.debug("createJobSessionJob() referJob jobunitId=" + referJob.getId().getJobunitId() + " jobId="
                + referJob.getId().getJobId());
        parentJobunitId = referJob.getId().getJobunitId();
        parentJobId = referJob.getId().getJobId();
        referJob = null;
    } else if (jobIdMap != null && !jobIdMap.isEmpty()) {
        //???????????ID?
        parentJobId = jobIdMap.get(job.getParentJobId());
        m_log.debug("rename jobId at parentJobSessionJobEntity:" + job.getParentJobId() + "->" + parentJobId);
    }

    if (first) {
        parentJobSessionJobEntity = QueryUtil.getJobSessionJobPK(sessionId, TOP_JOBUNIT_ID, TOP_JOB_ID);
    } else {
        parentJobSessionJobEntity = QueryUtil.getJobSessionJobPK(sessionId, parentJobunitId, parentJobId);
    }

    //?/?????UnitId?jobID??????
    if (job.getJobType() == JobConstant.TYPE_REFERJOB || job.getJobType() == JobConstant.TYPE_REFERJOBNET) {
        referJob = job;
        //????
        job = QueryUtil.getJobMstPK(job.getReferJobUnitId(), job.getReferJobId());
    }

    //?????????ID?????????
    if (referJob != null && referJob.getJobType() == JobConstant.TYPE_REFERJOBNET) {
        // ?????????(????JOB??ID)
        // ????????????????????1????
        jobIdMap = getRenameJobIdMap(referJob.getId().getJobId(), job, null);
    }

    //JobSessionJob?
    //jobIdMap??????????????jobId??
    //??job?????jobId?????jobId?JobSessionJobEntity,JobInfoEntity??
    if (jobIdMap != null && !jobIdMap.isEmpty() && jobIdMap.get(jobId) != null) {
        jobId = jobIdMap.get(jobId);
        m_log.debug("rename jobId at JobSessionJobEntity:" + job.getId().getJobId() + "->" + jobId);
    }

    JobSessionJobEntity jobSessionJobEntity = new JobSessionJobEntity(jobSessionEntity, jobunitId, jobId);
    // ??
    jtm.checkEntityExists(JobSessionJobEntity.class, jobSessionJobEntity.getId());
    jobSessionJobEntity.setParentJobunitId(parentJobSessionJobEntity.getId().getJobunitId());
    jobSessionJobEntity.setParentJobId(parentJobSessionJobEntity.getId().getJobId());
    jobSessionJobEntity.setStartDate(null);
    jobSessionJobEntity.setEndDate(null);
    jobSessionJobEntity.setEndStatus(null);
    jobSessionJobEntity.setResult(null);
    jobSessionJobEntity.setEndStausCheckFlg(EndStatusCheckConstant.NO_WAIT_JOB);
    jobSessionJobEntity.setDelayNotifyFlg(DelayNotifyConstant.NONE);
    jobSessionJobEntity.setEndValue(null);

    //
    if (first) {
        // ??????
        jobSessionJobEntity.setStatus(StatusConstant.TYPE_WAIT);
    } else if (job.getSuspend() != null && job.getSuspend().booleanValue()) {
        //?
        jobSessionJobEntity.setStatus(StatusConstant.TYPE_RESERVING);
    } else if (job.getSkip() != null && job.getSkip().booleanValue()) {
        //
        jobSessionJobEntity.setStatus(StatusConstant.TYPE_SKIP);
    } else {
        //?
        jobSessionJobEntity.setStatus(StatusConstant.TYPE_WAIT);
    }

    //JobInfoEntity?
    JobInfoEntity jobInfoEntity = new JobInfoEntity(jobSessionJobEntity);
    // ??
    jtm.checkEntityExists(JobInfoEntity.class, jobInfoEntity.getId());
    jobInfoEntity.setJobName(job.getJobName());
    jobInfoEntity.setDescription(job.getDescription());
    jobInfoEntity.setJobType(job.getJobType());
    jobInfoEntity.setRegisteredModule(job.isRegisteredModule());
    jobInfoEntity.setRegDate(job.getRegDate());
    jobInfoEntity.setUpdateDate(job.getUpdateDate());
    jobInfoEntity.setRegUser(job.getRegUser());
    jobInfoEntity.setUpdateUser(job.getUpdateUser());
    jobInfoEntity.setIconId(job.getIconId());

    //?????
    //??
    if (job.getJobType() == JobConstant.TYPE_JOBNET || job.getJobType() == JobConstant.TYPE_APPROVALJOB
            || job.getJobType() == JobConstant.TYPE_JOB || job.getJobType() == JobConstant.TYPE_FILEJOB
            || job.getJobType() == JobConstant.TYPE_MONITORJOB) {
        //??????????
        JobMstEntity tmp = null;
        if (referJob != null) {
            tmp = referJob;
        } else {
            tmp = job;
        }
        jobInfoEntity.setConditionType(tmp.getConditionType());
        jobInfoEntity.setUnmatchEndFlg(tmp.getUnmatchEndFlg());
        jobInfoEntity.setUnmatchEndStatus(tmp.getUnmatchEndStatus());
        jobInfoEntity.setUnmatchEndValue(tmp.getUnmatchEndValue());
        jobInfoEntity.setSkipEndStatus(job.getSkipEndStatus());
        jobInfoEntity.setSkipEndValue(job.getSkipEndValue());
        jobInfoEntity.setCalendarId(job.getCalendarId());
        jobInfoEntity.setCalendarEndStatus(job.getCalendarEndStatus());
        jobInfoEntity.setCalendarEndValue(job.getCalendarEndValue());
        jobInfoEntity.setStartDelaySession(job.getStartDelaySession());
        jobInfoEntity.setStartDelaySessionValue(job.getStartDelaySessionValue());
        jobInfoEntity.setStartDelayTime(job.getStartDelayTime());
        jobInfoEntity.setStartDelayTimeValue(job.getStartDelayTimeValue());
        jobInfoEntity.setStartDelayConditionType(job.getStartDelayConditionType());
        jobInfoEntity.setStartDelayNotify(job.getStartDelayNotify());
        jobInfoEntity.setStartDelayNotifyPriority(job.getStartDelayNotifyPriority());
        jobInfoEntity.setStartDelayOperation(job.getStartDelayOperation());
        jobInfoEntity.setStartDelayOperationType(job.getStartDelayOperationType());
        jobInfoEntity.setStartDelayOperationEndStatus(job.getStartDelayOperationEndStatus());
        jobInfoEntity.setStartDelayOperationEndValue(job.getStartDelayOperationEndValue());
        jobInfoEntity.setEndDelaySession(job.getEndDelaySession());
        jobInfoEntity.setEndDelaySessionValue(job.getEndDelaySessionValue());
        jobInfoEntity.setEndDelayJob(job.getEndDelayJob());
        jobInfoEntity.setEndDelayJobValue(job.getEndDelayJobValue());
        jobInfoEntity.setEndDelayTime(job.getEndDelayTime());
        jobInfoEntity.setEndDelayTimeValue(job.getEndDelayTimeValue());
        jobInfoEntity.setEndDelayConditionType(job.getEndDelayConditionType());
        jobInfoEntity.setEndDelayNotify(job.getEndDelayNotify());
        jobInfoEntity.setEndDelayNotifyPriority(job.getEndDelayNotifyPriority());
        jobInfoEntity.setEndDelayOperation(job.getEndDelayOperation());
        jobInfoEntity.setEndDelayOperationType(job.getEndDelayOperationType());
        jobInfoEntity.setEndDelayOperationEndStatus(job.getEndDelayOperationEndStatus());
        jobInfoEntity.setEndDelayOperationEndValue(job.getEndDelayOperationEndValue());

        jobInfoEntity.setMultiplicityNotify(job.getMultiplicityNotify());
        jobInfoEntity.setMultiplicityNotifyPriority(job.getMultiplicityNotifyPriority());
        jobInfoEntity.setMultiplicityOperation(job.getMultiplicityOperation());
        jobInfoEntity.setMultiplicityEndValue(job.getMultiplicityEndValue());
    }

    //
    if (job.getJobType() == JobConstant.TYPE_JOB) {
        jobInfoEntity.setFacilityId(job.getFacilityId());
        jobInfoEntity.setProcessMode(job.getProcessMode());
        if (triggerInfo.getJobCommand()) {
            jobInfoEntity.setStartCommand(triggerInfo.getJobCommandText());
        } else {
            jobInfoEntity.setStartCommand(job.getStartCommand());
        }
        jobInfoEntity.setStopType(job.getStopType());
        jobInfoEntity.setStopCommand(job.getStopCommand());
        jobInfoEntity.setSpecifyUser(job.getSpecifyUser());
        jobInfoEntity.setEffectiveUser(job.getEffectiveUser());
        jobInfoEntity.setMessageRetryEndFlg(job.getMessageRetryEndFlg());
        jobInfoEntity.setMessageRetryEndValue(job.getMessageRetryEndValue());
        jobInfoEntity.setArgumentJobId(job.getArgumentJobId());
        jobInfoEntity.setArgument(job.getArgument());
        jobInfoEntity.setMessageRetry(job.getMessageRetry());
        jobInfoEntity.setCommandRetryFlg(job.getCommandRetryFlg());
        jobInfoEntity.setCommandRetry(job.getCommandRetry());

        // JobCommandParamInfoEntity??
        List<JobCommandParamMstEntity> JobCommandParamEntityList = job.getJobCommandParamEntities();
        if (JobCommandParamEntityList != null) {
            List<JobCommandParamInfoEntity> jobCommandParamInfoEntityList = new ArrayList<>();
            for (JobCommandParamMstEntity jobCommandParamEntity : JobCommandParamEntityList) {
                // ?
                JobCommandParamInfoEntity jobCommandParamInfoEntity = new JobCommandParamInfoEntity(
                        jobInfoEntity, jobInfoEntity.getId().getJobunitId(), jobInfoEntity.getId().getJobId(),
                        jobCommandParamEntity.getId().getParamId());
                jobCommandParamInfoEntity
                        .setJobStandardOutputFlg(jobCommandParamEntity.getJobStandardOutputFlg());
                jobCommandParamInfoEntity.setValue(jobCommandParamEntity.getValue());
                jobCommandParamInfoEntityList.add(jobCommandParamInfoEntity);
            }
            jobInfoEntity.setJobCommandParamInfoEntities(jobCommandParamInfoEntityList);
        }
        jobInfoEntity.setManagerDistribution(job.getManagerDistribution());
        jobInfoEntity.setScriptName(job.getScriptName());
        jobInfoEntity.setScriptEncoding(job.getScriptEncoding());
        jobInfoEntity.setScriptContent(job.getScriptContent());

        // ?
        List<JobEnvVariableMstEntity> jobEnvVariableMstEntityList = job.getJobEnvVariableMstEntities();
        if (jobEnvVariableMstEntityList != null) {
            for (JobEnvVariableMstEntity jobEnvVariableMstEntity : jobEnvVariableMstEntityList) {
                // ?
                JobEnvVariableInfoEntity jobEnvVariableInfoEntity = new JobEnvVariableInfoEntity(jobInfoEntity,
                        jobEnvVariableMstEntity.getId().getEnvVariableId());
                // ??
                jtm.checkEntityExists(JobEnvVariableInfoEntity.class, jobEnvVariableInfoEntity.getId());
                jobEnvVariableInfoEntity.setValue(jobEnvVariableMstEntity.getValue());
                jobEnvVariableInfoEntity.setDescription(jobEnvVariableMstEntity.getDescription());
            }
        }
    }

    //?
    if (job.getJobType() == JobConstant.TYPE_FILEJOB) {
        jobInfoEntity.setProcessMode(job.getProcessMode());
        jobInfoEntity.setSrcFacilityId(job.getSrcFacilityId());
        jobInfoEntity.setDestFacilityId(job.getDestFacilityId());
        jobInfoEntity.setSrcFile(job.getSrcFile());
        jobInfoEntity.setSrcWorkDir(job.getSrcWorkDir());
        jobInfoEntity.setDestDirectory(job.getDestDirectory());
        jobInfoEntity.setDestWorkDir(job.getDestWorkDir());
        jobInfoEntity.setCompressionFlg(job.getCompressionFlg());
        jobInfoEntity.setCheckFlg(job.getCheckFlg());
        jobInfoEntity.setSpecifyUser(job.getSpecifyUser());
        jobInfoEntity.setEffectiveUser(job.getEffectiveUser());
        jobInfoEntity.setMessageRetry(job.getMessageRetry());
        jobInfoEntity.setMessageRetryEndFlg(job.getMessageRetryEndFlg());
        jobInfoEntity.setMessageRetryEndValue(job.getMessageRetryEndValue());
        jobInfoEntity.setCommandRetryFlg(job.getCommandRetryFlg());
        jobInfoEntity.setCommandRetry(job.getCommandRetry());
    }

    //?
    if (job.getJobType() == JobConstant.TYPE_APPROVALJOB) {
        jobInfoEntity.setApprovalReqRoleId(job.getApprovalReqRoleId());
        jobInfoEntity.setApprovalReqUserId(job.getApprovalReqUserId());
        jobInfoEntity.setApprovalReqSentence(job.getApprovalReqSentence());
        jobInfoEntity.setApprovalReqMailTitle(job.getApprovalReqMailTitle());
        jobInfoEntity.setApprovalReqMailBody(job.getApprovalReqMailBody());
        jobInfoEntity.setUseApprovalReqSentence(job.isUseApprovalReqSentence());
        // ID(????ID)
        jobInfoEntity.setFacilityId(jobSessionJobEntity.getOwnerRoleId());
        // ???????
        jobInfoEntity.setProcessMode(ProcessingMethodConstant.TYPE_ALL_NODE);
        jobInfoEntity.setMessageRetryEndFlg(false);
        jobInfoEntity.setMessageRetry(1);
        jobInfoEntity.setCommandRetryFlg(false);
        jobInfoEntity.setStopType(CommandStopTypeConstant.DESTROY_PROCESS);
        jobInfoEntity.setStopCommand("");
    }

    //
    if (job.getJobType() == JobConstant.TYPE_MONITORJOB) {
        jobInfoEntity.setFacilityId(job.getFacilityId());
        jobInfoEntity.setStopType(CommandStopTypeConstant.DESTROY_PROCESS);
        jobInfoEntity.setProcessMode(job.getProcessMode());
        jobInfoEntity.setMessageRetryEndFlg(job.getMessageRetryEndFlg());
        jobInfoEntity.setMessageRetryEndValue(job.getMessageRetryEndValue());
        jobInfoEntity.setArgumentJobId(job.getArgumentJobId());
        jobInfoEntity.setArgument(job.getArgument());
        jobInfoEntity.setMessageRetry(job.getMessageRetry());
        jobInfoEntity.setMessageRetryEndFlg(job.getMessageRetryEndFlg());
        jobInfoEntity.setMessageRetryEndValue(job.getMessageRetryEndValue());
        jobInfoEntity.setCommandRetryFlg(job.getCommandRetryFlg());
        jobInfoEntity.setCommandRetry(job.getCommandRetry());
        jobInfoEntity.setMonitorId(job.getMonitorId());
        jobInfoEntity.setMonitorInfoEndValue(job.getMonitorInfoEndValue());
        jobInfoEntity.setMonitorWarnEndValue(job.getMonitorWarnEndValue());
        jobInfoEntity.setMonitorCriticalEndValue(job.getMonitorCriticalEndValue());
        jobInfoEntity.setMonitorUnknownEndValue(job.getMonitorUnknownEndValue());
        jobInfoEntity.setMonitorWaitTime(job.getMonitorWaitTime());
        jobInfoEntity.setMonitorWaitEndValue(job.getMonitorWaitEndValue());
    }

    // ??
    // first:??????(suspend,skip,calendar)?????
    if (!first) {
        jobInfoEntity.setSuspend(job.getSuspend());
        jobInfoEntity.setSkip(job.getSkip());
        jobInfoEntity.setCalendar(job.getCalendar());
        jobInfoEntity.setStartDelay(job.getStartDelay());
        jobInfoEntity.setEndDelay(job.getEndDelay());
        //??????????
        JobMstEntity tmp = null;
        if (referJob != null) {
            tmp = referJob;
        } else {
            tmp = job;
        }
        //???(?????????NULL)
        if (triggerInfo.getJobWaitTime()) {
            jobInfoEntity.setStartTime(null);
        } else {
            jobInfoEntity.setStartTime(tmp.getStartTime());
            jobInfoEntity.setStartTimeDescription(tmp.getStartTimeDescription());
            m_log.debug("getStartTime = " + tmp.getStartTime());
            m_log.debug("getStartTimeDescription = " + tmp.getStartTimeDescription());
        }

        //????(????????NULL)
        if (triggerInfo.getJobWaitMinute()) {
            jobInfoEntity.setStartMinute(null);
        } else {
            jobInfoEntity.setStartMinute(tmp.getStartMinute());
            jobInfoEntity.setStartMinuteDescription(tmp.getStartMinuteDescription());
            m_log.debug("getStartMinute = " + tmp.getStartTime());
            m_log.debug("getStartTimeDescription = " + tmp.getStartMinuteDescription());
        }

        //JobStartJobInfoEntity?
        List<JobStartJobMstEntity> jobStartJobMstEntityList = tmp.getJobStartJobMstEntities();
        if (jobStartJobMstEntityList != null) {
            for (JobStartJobMstEntity jobStartJobMstEntity : jobStartJobMstEntityList) {
                //jobIdMap??????????????????jobId??
                //????jobId????job?????jobId?????jobId?JobStartJobInfoEntity??
                String renameTargetJobId = null;
                if (jobIdMap != null && !jobIdMap.isEmpty()) {
                    renameTargetJobId = jobIdMap.get(jobStartJobMstEntity.getId().getTargetJobId());
                    m_log.debug("rename jobId at JobStartJobMstEntity:"
                            + jobStartJobMstEntity.getId().getTargetJobId() + "->" + renameTargetJobId);
                }
                // ?
                JobStartJobInfoEntity jobStartJobInfoEntity = new JobStartJobInfoEntity(jobInfoEntity,
                        jobStartJobMstEntity.getId().getTargetJobunitId(),
                        (renameTargetJobId != null ? renameTargetJobId
                                : jobStartJobMstEntity.getId().getTargetJobId()),
                        jobStartJobMstEntity.getId().getTargetJobType(),
                        jobStartJobMstEntity.getId().getTargetJobEndValue());
                jobStartJobInfoEntity.setTargetJobDescription(jobStartJobMstEntity.getTargetJobDescription());
                m_log.debug("getTargetJobType = " + jobStartJobMstEntity.getId().getTargetJobType());
                m_log.debug("getTargetJobId = " + (renameTargetJobId != null ? renameTargetJobId
                        : jobStartJobMstEntity.getId().getTargetJobId()));
                m_log.debug("getTargetJobEndValue = " + jobStartJobMstEntity.getId().getTargetJobEndValue());
                m_log.debug("getTargetJobDescription = " + jobStartJobMstEntity.getTargetJobDescription());
                // ??
                jtm.checkEntityExists(JobStartJobInfoEntity.class, jobStartJobInfoEntity.getId());
            }
        }

        //JobStartParamMstEntity?
        List<JobStartParamMstEntity> jobStartParamMstEntityList = tmp.getJobStartParamMstEntities();
        if (jobStartParamMstEntityList != null) {
            for (JobStartParamMstEntity jobStartParamMstEntity : jobStartParamMstEntityList) {
                JobStartParamInfoEntity jobStartParamInfoEntity = new JobStartParamInfoEntity(jobInfoEntity,
                        jobStartParamMstEntity.getId().getStartDecisionValue01(),
                        jobStartParamMstEntity.getId().getStartDecisionValue02(),
                        jobStartParamMstEntity.getId().getTargetJobType(),
                        jobStartParamMstEntity.getId().getStartDecisionCondition());
                jobStartParamInfoEntity.setDecisionDescription(jobStartParamMstEntity.getDecisionDescription());
                m_log.debug("getTargetJobType = " + jobStartParamMstEntity.getId().getTargetJobType());
                m_log.debug("getStartDecisionValue01 = "
                        + jobStartParamMstEntity.getId().getStartDecisionValue01());
                m_log.debug("getStartDecisionCondition = "
                        + jobStartParamMstEntity.getId().getStartDecisionCondition());
                m_log.debug("getStartDecisionValue02 = "
                        + jobStartParamMstEntity.getId().getStartDecisionValue02());
                m_log.debug("getDecisionDescription = " + jobStartParamMstEntity.getDecisionDescription());
                // ??
                jtm.checkEntityExists(JobStartParamInfoEntity.class, jobStartParamInfoEntity.getId());
            }
        }
    } else {
        jobInfoEntity.setSuspend(false);
        jobInfoEntity.setSkip(false);
        jobInfoEntity.setCalendar(false);
        jobInfoEntity.setStartDelay(false);
        jobInfoEntity.setEndDelay(false);
    }

    // JobParamInfoEntity?
    // ??????
    if (first) {
        // ?
        JobMstEntity jobunit = QueryUtil.getJobMstPK(jobunitId, jobunitId);
        List<JobParamMstEntity> jobParamMstEntityList = jobunit.getJobParamMstEntities();
        if (jobParamMstEntityList != null) {
            for (JobParamMstEntity jobParamMstEntity : jobParamMstEntityList) {
                // ?
                JobParamInfoEntity jobParamInfoEntity = new JobParamInfoEntity(jobInfoEntity,
                        jobParamMstEntity.getId().getParamId());
                // ??
                jtm.checkEntityExists(JobParamInfoEntity.class, jobParamInfoEntity.getId());
                jobParamInfoEntity.setParamType(jobParamMstEntity.getParamType());
                jobParamInfoEntity.setDescription(jobParamMstEntity.getDescription());
                //?
                String value = null;
                if (jobParamMstEntity.getParamType() == JobParamTypeConstant.TYPE_USER) {
                    //
                    value = jobParamMstEntity.getValue();
                }
                jobParamInfoEntity.setValue(value);
            }
        }
        // ??
        for (Map.Entry<String, String> entry : ParameterUtil.createParamInfo(info).entrySet()) {
            JobParamInfoEntity jobParamInfoEntity = new JobParamInfoEntity(jobInfoEntity, entry.getKey());
            jobParamInfoEntity.setValue(entry.getValue());
            jobParamInfoEntity.setParamType(JobParamTypeConstant.TYPE_SYSTEM_JOB);
        }
        // ?
        for (Map.Entry<String, String> entry : ParameterUtil.createParamInfo(triggerInfo).entrySet()) {
            JobParamInfoEntity jobParamInfoEntity = new JobParamInfoEntity(jobInfoEntity, entry.getKey());
            jobParamInfoEntity.setValue(entry.getValue());
            jobParamInfoEntity.setParamType(JobParamTypeConstant.TYPE_SYSTEM_JOB);
        }
        // ??
        if (triggerInfo.getTrigger_type() == JobTriggerTypeConstant.TYPE_SCHEDULE
                || triggerInfo.getTrigger_type() == JobTriggerTypeConstant.TYPE_FILECHECK) {
            JobKickEntity jobKickEntity = em.find(JobKickEntity.class, triggerInfo.getJobkickId(),
                    ObjectPrivilegeMode.NONE);
            if (jobKickEntity.getJobRuntimeParamEntities() != null) {
                for (JobRuntimeParamEntity jobRuntimeParamEntity : jobKickEntity.getJobRuntimeParamEntities()) {
                    JobParamInfoEntityPK jobParamInfoEntityPK = new JobParamInfoEntityPK(
                            jobInfoEntity.getId().getSessionId(), jobInfoEntity.getId().getJobunitId(),
                            jobInfoEntity.getId().getJobId(), jobRuntimeParamEntity.getId().getParamId());
                    JobParamInfoEntity jobParamInfoEntity = em.find(JobParamInfoEntity.class,
                            jobParamInfoEntityPK, ObjectPrivilegeMode.READ);
                    if (jobParamInfoEntity == null) {
                        jobParamInfoEntity = new JobParamInfoEntity(jobInfoEntity,
                                jobRuntimeParamEntity.getId().getParamId());
                    }
                    jobParamInfoEntity.setValue(jobRuntimeParamEntity.getDefaultValue());
                    jobParamInfoEntity.setParamType(JobParamTypeConstant.TYPE_RUNTIME);
                }
            }
        }
        // 
        if (triggerInfo.getJobRuntimeParamList() != null) {
            for (JobRuntimeParam jobRuntimeParam : triggerInfo.getJobRuntimeParamList()) {
                JobParamInfoEntityPK jobParamInfoEntityPK = new JobParamInfoEntityPK(
                        jobInfoEntity.getId().getSessionId(), jobInfoEntity.getId().getJobunitId(),
                        jobInfoEntity.getId().getJobId(), jobRuntimeParam.getParamId());
                JobParamInfoEntity jobParamInfoEntity = em.find(JobParamInfoEntity.class, jobParamInfoEntityPK,
                        ObjectPrivilegeMode.READ);
                if (jobParamInfoEntity == null) {
                    jobParamInfoEntity = new JobParamInfoEntity(jobInfoEntity, jobRuntimeParam.getParamId());
                }
                jobParamInfoEntity.setValue(jobRuntimeParam.getValue());
                jobParamInfoEntity.setParamType(JobParamTypeConstant.TYPE_RUNTIME);
            }
        }
    }
    //(JobSessionJobEntity)
    Map<String, String> jobSessionParams = null;
    if (job.getFacilityId() != null) {
        //ID?
        String facilityId = job.getFacilityId();
        if ((job.getJobType() == JobConstant.TYPE_JOB || job.getJobType() == JobConstant.TYPE_MONITORJOB)
                && SystemParameterConstant.isParam(facilityId, SystemParameterConstant.FACILITY_ID)) {
            String paramValue = ParameterUtil.getJobSessionParamValue(SystemParameterConstant.FACILITY_ID,
                    sessionId, jobSessionParams);
            if (paramValue != null) {
                facilityId = paramValue;
            }
        }
        String scopePath = new RepositoryControllerBean().getFacilityPath(facilityId, null);
        jobSessionJobEntity.setScopeText(scopePath);
    } else if (job.getJobType() == JobConstant.TYPE_APPROVALJOB) {

        jobSessionJobEntity.setScopeText(jobSessionJobEntity.getOwnerRoleId());
    } else {
        jobSessionJobEntity.setScopeText(null);
    }

    //JobSessionNodeEntity?
    if (job.getJobType() == JobConstant.TYPE_JOB || job.getJobType() == JobConstant.TYPE_MONITORJOB) {
        //ID?
        String facilityId = job.getFacilityId();
        if (SystemParameterConstant.isParam(facilityId, SystemParameterConstant.FACILITY_ID)) {
            String paramValue = ParameterUtil.getJobSessionParamValue(SystemParameterConstant.FACILITY_ID,
                    sessionId, jobSessionParams);
            if (paramValue != null) {
                facilityId = paramValue;
            }
        }
        ArrayList<String> nodeIdList = new ArrayList<String>();
        if (facilityId != null) {
            //?ID?
            nodeIdList = new RepositoryControllerBean().getExecTargetFacilityIdList(facilityId,
                    jobSessionJobEntity.getOwnerRoleId());
        }
        if (nodeIdList != null) {
            for (String nodeId : nodeIdList) {
                //???
                NodeInfo nodeInfo = new RepositoryControllerBean().getNode(nodeId);
                // ?
                JobSessionNodeEntity jobSessionNodeEntity = new JobSessionNodeEntity(jobSessionJobEntity,
                        nodeId);
                // ??
                jtm.checkEntityExists(JobSessionNodeEntity.class, jobSessionNodeEntity.getId());
                jobSessionNodeEntity.setStatus(StatusConstant.TYPE_WAIT);
                jobSessionNodeEntity.setStartDate(null);
                jobSessionNodeEntity.setEndDate(null);
                jobSessionNodeEntity.setEndValue(null);
                jobSessionNodeEntity.setMessage(null);
                jobSessionNodeEntity.setRetryCount(0);
                jobSessionNodeEntity.setResult(null);
                jobSessionNodeEntity.setNodeName(nodeInfo.getFacilityName());
            }
        }
    }
    // ????JobSessionNodeEntity???????
    if (job.getJobType() == JobConstant.TYPE_APPROVALJOB) {
        // ID/???(????ID)
        RoleInfo roleInfo = new AccessControllerBean().getRoleInfo(jobSessionJobEntity.getOwnerRoleId());
        JobSessionNodeEntity jobSessionNodeEntity = new JobSessionNodeEntity(jobSessionJobEntity,
                jobSessionJobEntity.getOwnerRoleId());
        // ??
        jtm.checkEntityExists(JobSessionNodeEntity.class, jobSessionNodeEntity.getId());
        jobSessionNodeEntity.setStatus(StatusConstant.TYPE_WAIT);
        jobSessionNodeEntity.setStartDate(null);
        jobSessionNodeEntity.setEndDate(null);
        jobSessionNodeEntity.setEndValue(null);
        jobSessionNodeEntity.setMessage(null);
        jobSessionNodeEntity.setRetryCount(0);
        jobSessionNodeEntity.setResult(null);
        jobSessionNodeEntity.setNodeName(roleInfo.getRoleName());
        m_log.debug("getRoleName():" + roleInfo.getRoleName());
        // (????)
        if (triggerInfo.getTrigger_type() == JobTriggerTypeConstant.TYPE_MANUAL) {
            int pre = triggerInfo.getTrigger_info().indexOf("(");
            int post = triggerInfo.getTrigger_info().length() - 1;
            String userid = triggerInfo.getTrigger_info().substring(pre + 1, post);
            m_log.debug("userid:" + userid);
            jobSessionNodeEntity.setApprovalRequestUser(userid);
        }
        // ?????
        // ?(JobParamInfoEntity?)?????????????
        // ??
        String reqSentence = jobInfoEntity.getApprovalReqSentence();
        reqSentence = ParameterUtil.replaceSessionParameterValue(sessionId, jobInfoEntity.getFacilityId(),
                jobInfoEntity.getApprovalReqSentence());
        // ???????(#[RETURN:jobid:facilityId])?null??????????
        jobInfoEntity.setApprovalReqSentence(reqSentence);

        // ????
        String mailTitle = jobInfoEntity.getApprovalReqMailTitle();
        mailTitle = ParameterUtil.replaceSessionParameterValue(sessionId, jobInfoEntity.getFacilityId(),
                jobInfoEntity.getApprovalReqMailTitle());
        // ???????(#[RETURN:jobid:facilityId])?null??????????
        jobInfoEntity.setApprovalReqMailTitle(mailTitle);

        // ??
        String mailBody = jobInfoEntity.getApprovalReqMailBody();
        mailBody = ParameterUtil.replaceSessionParameterValue(sessionId, jobInfoEntity.getFacilityId(),
                jobInfoEntity.getApprovalReqMailBody());
        // ???????(#[RETURN:jobid:facilityId])?null??????????
        jobInfoEntity.setApprovalReqMailBody(mailBody);
    }

    jobInfoEntity.setBeginPriority(job.getBeginPriority());
    jobInfoEntity.setNormalPriority(job.getNormalPriority());
    jobInfoEntity.setWarnPriority(job.getWarnPriority());
    jobInfoEntity.setAbnormalPriority(job.getAbnormalPriority());
    String infoNotifyGroupId = NotifyGroupIdGenerator.generate(jobInfoEntity);
    jobInfoEntity.setNotifyGroupId(infoNotifyGroupId);

    // ?
    // 
    jobInfoEntity.setNormalEndValue(job.getNormalEndValue());
    jobInfoEntity.setNormalEndValueFrom(job.getNormalEndValueFrom());
    jobInfoEntity.setNormalEndValueTo(job.getNormalEndValueTo());
    // 
    jobInfoEntity.setWarnEndValue(job.getWarnEndValue());
    jobInfoEntity.setWarnEndValueFrom(job.getWarnEndValueFrom());
    jobInfoEntity.setWarnEndValueTo(job.getWarnEndValueTo());
    // 
    jobInfoEntity.setAbnormalEndValue(job.getAbnormalEndValue());
    jobInfoEntity.setAbnormalEndValueFrom(job.getAbnormalEndValueFrom());
    jobInfoEntity.setAbnormalEndValueTo(job.getAbnormalEndValueTo());

    // ????ID????
    List<NotifyRelationInfo> ct = new NotifyControllerBean().getNotifyRelation(job.getNotifyGroupId());
    // JobNoticeInfo?ID?????
    List<NotifyRelationInfo> infoNotifyRelationList = new ArrayList<>();
    for (NotifyRelationInfo relation : ct) {
        NotifyRelationInfo nri = new NotifyRelationInfo(infoNotifyGroupId, relation.getNotifyId());
        nri.setNotifyType(relation.getNotifyType());
        infoNotifyRelationList.add(nri);
    }
    // Job?NotifyRelationInfo??????
    new NotifyControllerBean().addNotifyRelation(infoNotifyRelationList);

    //?????
    // ???????????????
    if (job.getJobType() == JobConstant.TYPE_FILEJOB) {
        if (CreateHulftJob.isHulftMode()) {
            new CreateHulftJob().createHulftDetailJob(jobInfoEntity);
        } else {
            // ?????????????ID??
            new CreateFileJob().createGetFileListJob(jobInfoEntity, job.getId().getJobId());
        }
    }

    // ????
    List<JobMstEntity> childJobMstEntities = em
            .createNamedQuery("JobMstEntity.findByParentJobunitIdAndJobId", JobMstEntity.class)
            .setParameter("parentJobunitId", job.getId().getJobunitId())
            .setParameter("parentJobId", job.getId().getJobId()).getResultList();

    if (childJobMstEntities != null) {
        for (JobMstEntity childJob : childJobMstEntities) {
            // ??
            createJobSessionJob(childJob, sessionId, info, false, triggerInfo, referJob, jobIdMap);
        }
    }
    return jobSessionJobEntity.getId();
}

From source file:org.broadleafcommerce.core.order.service.legacy.LegacyOrderServiceImpl.java

protected boolean bundleItemMatches(BundleOrderItem item1, BundleOrderItem item2) {
    if (item1.getSku() != null && item2.getSku() != null) {
        return item1.getSku().getId().equals(item2.getSku().getId());
    }//from   w w  w .ja  v a2 s  . c  o  m

    // Otherwise, scan the items.
    HashMap<Long, Integer> skuMap = new HashMap<Long, Integer>();
    for (DiscreteOrderItem item : item1.getDiscreteOrderItems()) {
        if (skuMap.get(item.getSku().getId()) == null) {
            skuMap.put(item.getSku().getId(), Integer.valueOf(item.getQuantity()));
        } else {
            Integer qty = skuMap.get(item.getSku().getId());
            skuMap.put(item.getSku().getId(), Integer.valueOf(qty + item.getQuantity()));
        }
    }

    // Now consume the quantities in the map
    for (DiscreteOrderItem item : item2.getDiscreteOrderItems()) {
        if (skuMap.containsKey(item.getSku().getId())) {
            Integer qty = skuMap.get(item.getSku().getId());
            Integer newQty = Integer.valueOf(qty - item.getQuantity());
            if (newQty.intValue() == 0) {
                skuMap.remove(item.getSku().getId());
            } else if (newQty.intValue() > 0) {
                skuMap.put(item.getSku().getId(), newQty);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    return skuMap.isEmpty();
}