List of usage examples for java.text DateFormat SHORT
int SHORT
To view the source code for java.text DateFormat SHORT.
Click Source Link
From source file:fr.paris.lutece.portal.service.admin.AdminUserService.java
/** * Update the user expiration date with new values, and notify him with an email if his account was close to expire. * @param user The user to update//from w w w . j av a2s .com */ @SuppressWarnings("deprecation") public static void updateUserExpirationDate(AdminUser user) { if (user == null) { return; } Timestamp newExpirationDate = getAccountMaxValidDate(); Timestamp maxValidDate = user.getAccountMaxValidDate(); // We update the user account AdminUserHome.updateUserExpirationDate(user.getUserId(), newExpirationDate); // We notify the user String strUserMail = user.getEmail(); int nbDaysBeforeFirstAlert = AdminUserService .getIntegerSecurityParameter(PARAMETER_TIME_BEFORE_ALERT_ACCOUNT); if (maxValidDate != null) { Timestamp firstAlertMaxDate = new Timestamp( maxValidDate.getTime() - DateUtil.convertDaysInMiliseconds(nbDaysBeforeFirstAlert)); Timestamp currentTimestamp = new Timestamp(new java.util.Date().getTime()); if ((currentTimestamp.getTime() > firstAlertMaxDate.getTime()) && StringUtils.isNotBlank(strUserMail)) { AdminUser completeUser = AdminUserHome.findByPrimaryKey(user.getUserId()); String strBody = DatabaseTemplateService .getTemplateFromKey(PARAMETER_ACCOUNT_REACTIVATED_MAIL_BODY); DefaultUserParameter defaultUserParameter = DefaultUserParameterHome .findByKey(PARAMETER_ACCOUNT_REACTIVATED_MAIL_SENDER); String strSender = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); defaultUserParameter = DefaultUserParameterHome .findByKey(PARAMETER_ACCOUNT_REACTIVATED_MAIL_SUBJECT); String strSubject = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); Map<String, String> model = new HashMap<String, String>(); DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); String accountMaxValidDate = dateFormat.format(new Date(newExpirationDate.getTime())); model.put(MARK_DATE_VALID, accountMaxValidDate); model.put(MARK_NAME, completeUser.getLastName()); model.put(MARK_FIRST_NAME, completeUser.getFirstName()); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, Locale.getDefault(), model); MailService.sendMailHtml(strUserMail, strSender, strSender, strSubject, template.getHtml()); } } }
From source file:org.yawlfoundation.yawl.resourcing.jsf.SessionBean.java
public String getInitCreatedDate() { if (chosenWIR != null) { return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) .format(chosenWIR.getEnablementTimeMs()); }//from ww w .j av a 2 s .c o m return ""; }
From source file:org.mifos.application.servicefacade.SavingsServiceFacadeWebTier.java
@Override public void updateSavingsAccountDetails(Long savingsId, String recommendedOrMandatoryAmount, List<CustomFieldDto> customFields) { MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserContext userContext = toUserContext(user); SavingsBO savingsAccount = this.savingsDao.findById(savingsId); savingsAccount.updateDetails(userContext); Set<AccountCustomFieldEntity> accountCustomFields = savingsAccount.getAccountCustomFields(); for (CustomFieldDto view : customFields) { boolean fieldPresent = false; if (CustomFieldType.DATE.getValue().equals(view.getFieldType()) && org.apache.commons.lang.StringUtils.isNotBlank(view.getFieldValue())) { try { SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, userContext.getPreferredLocale()); String userfmt = DateUtils.convertToCurrentDateFormat(format.toPattern()); view.setFieldValue(DateUtils.convertUserToDbFmt(view.getFieldValue(), userfmt)); } catch (InvalidDateException e) { throw new BusinessRuleException(e.getMessage(), e); }//from w w w . ja v a 2 s .c om } for (AccountCustomFieldEntity customFieldEntity : accountCustomFields) { if (customFieldEntity.getFieldId().equals(view.getFieldId())) { fieldPresent = true; customFieldEntity.setFieldValue(view.getFieldValue()); } } if (!fieldPresent) { accountCustomFields .add(new AccountCustomFieldEntity(savingsAccount, view.getFieldId(), view.getFieldValue())); } } Money amount = new Money(savingsAccount.getCurrency(), recommendedOrMandatoryAmount); try { this.transactionHelper.startTransaction(); this.transactionHelper.beginAuditLoggingFor(savingsAccount); savingsAccount.update(amount, accountCustomFields); this.savingsDao.save(savingsAccount); this.transactionHelper.commitTransaction(); } catch (BusinessRuleException e) { this.transactionHelper.rollbackTransaction(); throw new BusinessRuleException(e.getMessageKey(), e); } catch (Exception e) { this.transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } finally { this.transactionHelper.closeSession(); } }
From source file:com.concursive.connect.web.modules.wiki.utils.WikiToHTMLUtils.java
public static String toHtml(CustomFormField field, Wiki wiki, String contextPath) { // Return output based on type switch (field.getType()) { case CustomFormField.TEXTAREA: String textAreaValue = StringUtils.replace(field.getValue(), "^", CRLF); return StringUtils.toHtml(textAreaValue); case CustomFormField.SELECT: return StringUtils.toHtml(field.getValue()); case CustomFormField.CHECKBOX: if ("true".equals(field.getValue())) { return "Yes"; } else {// ww w . j a v a2 s . c o m return "No"; } case CustomFormField.CALENDAR: String calendarValue = field.getValue(); if (StringUtils.hasText(calendarValue)) { try { String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT, DateFormat.LONG, field.getValue()); Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate); Locale locale = Locale.getDefault(); int dateFormat = DateFormat.SHORT; SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat, locale); calendarValue = dateFormatter.format(timestamp); } catch (Exception e) { LOG.error("toHtml calendar", e); } } return StringUtils.toHtml(calendarValue); case CustomFormField.PERCENT: return StringUtils.toHtml(field.getValue()) + "%"; case CustomFormField.INTEGER: // Determine the value to display in the field String integerValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(integerValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not integer format: " + field.getValue()); } } return integerValue; case CustomFormField.FLOAT: // Determine the value to display in the field String decimalValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(decimalValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not decimal format: " + field.getValue()); } } return decimalValue; case CustomFormField.CURRENCY: // Use a currency for formatting String currencyCode = field.getValueCurrency(); if (currencyCode == null) { currencyCode = field.getCurrency(); } if (!StringUtils.hasText(currencyCode)) { currencyCode = "USD"; } try { NumberFormat formatter = NumberFormat.getCurrencyInstance(); if (currencyCode != null) { Currency currency = Currency.getInstance(currencyCode); formatter.setCurrency(currency); } return (StringUtils.toHtml(formatter.format(StringUtils.getDoubleNumber(field.getValue())))); } catch (Exception e) { LOG.error("toHtml currency", e); } return StringUtils.toHtml(field.getValue()); case CustomFormField.EMAIL: return StringUtils.toHtml(field.getValue()); case CustomFormField.PHONE: PhoneNumberBean phone = new PhoneNumberBean(); phone.setNumber(field.getValue()); PhoneNumberUtils.format(phone, Locale.getDefault()); return StringUtils.toHtml(phone.toString()); case CustomFormField.URL: String value = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(value)) { if (!value.contains("://")) { value = "http://" + value; } if (value.contains("://")) { return ("<a href=\"" + StringUtils.toHtml(value) + "\">" + StringUtils.toHtml(value) + "</a>"); } } return StringUtils.toHtml(value); case CustomFormField.IMAGE: String image = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(image)) { Project project = ProjectUtils.loadProject(wiki.getProjectId()); return ("<img src=\"" + contextPath + "/show/" + project.getUniqueId() + "/wiki-image/" + image + "\"/>"); } return StringUtils.toHtml(image); default: return StringUtils.toHtml(field.getValue()); } }
From source file:op.care.med.inventory.PnlInventory.java
private JPanel createContentPanel4(final MedStock stock) { // final String key = stock.getID() + ".xstock"; // if (!contentmap.containsKey(key)) { final JPanel pnlTX = new JPanel(new VerticalLayout()); // pnlTX.setLayout(new BoxLayout(pnlTX, BoxLayout.PAGE_AXIS)); pnlTX.setOpaque(true);//from w w w . j ava 2 s.co m // pnlTX.setBackground(Color.white); synchronized (lstInventories) { pnlTX.setBackground(getColor(SYSConst.light2, lstInventories.indexOf(stock.getInventory()) % 2 != 0)); } /*** * _ _ _ _______ __ * / \ __| | __| |_ _\ \/ / * / _ \ / _` |/ _` | | | \ / * / ___ \ (_| | (_| | | | / \ * /_/ \_\__,_|\__,_| |_| /_/\_\ * */ JideButton btnAddTX = GUITools.createHyperlinkButton("nursingrecords.inventory.newmedstocktx", SYSConst.icon22add, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new DlgTX(new MedStockTransaction(stock, BigDecimal.ONE, MedStockTransactionTools.STATE_EDIT_MANUAL), new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); final MedStockTransaction myTX = (MedStockTransaction) em.merge(o); MedStock myStock = em.merge(stock); em.lock(myStock, LockModeType.OPTIMISTIC); em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC); em.lock(em.merge(myTX.getStock().getInventory().getResident()), LockModeType.OPTIMISTIC); em.getTransaction().commit(); createCP4(myStock.getInventory()); buildPanel(); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager() .addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }); } }); btnAddTX.setEnabled(!stock.isClosed()); pnlTX.add(btnAddTX); /*** * ____ _ _ _ _______ __ * / ___|| |__ _____ __ __ _| | | |_ _\ \/ /___ * \___ \| '_ \ / _ \ \ /\ / / / _` | | | | | \ // __| * ___) | | | | (_) \ V V / | (_| | | | | | / \\__ \ * |____/|_| |_|\___/ \_/\_/ \__,_|_|_| |_| /_/\_\___/ * */ OPDE.getMainframe().setBlocked(true); OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100)); SwingWorker worker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { int progress = 0; List<MedStockTransaction> listTX = MedStockTransactionTools.getAll(stock); OPDE.getDisplayManager().setProgressBarMessage( new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size())); BigDecimal rowsum = MedStockTools.getSum(stock); // BigDecimal rowsum = MedStockTools.getSum(stock); // Collections.sort(stock.getStockTransaction()); for (final MedStockTransaction tx : listTX) { progress++; OPDE.getDisplayManager().setProgressBarMessage( new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size())); String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">" + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT) .format(tx.getPit()) + "<br/>[" + tx.getID() + "]" + "</td>" + "<td width=\"200\" align=\"center\">" + SYSTools.catchNull(tx.getText(), "--") + "</td>" + "<td width=\"100\" align=\"right\">" + NumberFormat.getNumberInstance().format(tx.getAmount()) + "</td>" + "<td width=\"100\" align=\"right\">" + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + NumberFormat.getNumberInstance().format(rowsum) + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + (stock.getTradeForm().isWeightControlled() ? "<td width=\"100\" align=\"right\">" + NumberFormat.getNumberInstance().format(tx.getWeight()) + "g" + "</td>" : "") + "<td width=\"100\" align=\"left\">" + SYSTools.anonymizeUser(tx.getUser().getUID()) + "</td>" + "</tr>" + "</table>" + "</font></html>"; rowsum = rowsum.subtract(tx.getAmount()); final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null); // pnlTitle.getLeft().addMouseListener(); if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) { /*** * ____ _ _______ __ * | _ \ ___| |_ _\ \/ / * | | | |/ _ \ | | | \ / * | |_| | __/ | | | / \ * |____/ \___|_| |_| /_/\_\ * */ final JButton btnDelTX = new JButton(SYSConst.icon22delete); btnDelTX.setPressedIcon(SYSConst.icon22deletePressed); btnDelTX.setAlignmentX(Component.RIGHT_ALIGNMENT); btnDelTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnDelTX.setContentAreaFilled(false); btnDelTX.setBorder(null); btnDelTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btndelete.tooltip")); btnDelTX.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>" + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT) .format(tx.getPit()) + " " + tx.getUser().getUID() + "</i><br/>" + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() { @Override public void execute(Object answer) { if (answer.equals(JOptionPane.YES_OPTION)) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); MedStockTransaction myTX = em.merge(tx); MedStock myStock = em.merge(stock); em.lock(em.merge( myTX.getStock().getInventory().getResident()), LockModeType.OPTIMISTIC); em.lock(myStock, LockModeType.OPTIMISTIC); em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC); em.remove(myTX); // myStock.getStockTransaction().remove(myTX); em.getTransaction().commit(); // synchronized (lstInventories) { // int indexInventory = lstInventories.indexOf(stock.getInventory()); // int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock); // lstInventories.get(indexInventory).getMedStocks().remove(stock); // lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock); // } // synchronized (linemap) { // linemap.remove(myTX); // } createCP4(myStock.getInventory()); buildPanel(); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage() .indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager() .addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }); } }); btnDelTX.setEnabled( !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL)); pnlTitle.getRight().add(btnDelTX); } /*** * _ _ _ _______ __ * | | | |_ __ __| | ___ |_ _\ \/ / * | | | | '_ \ / _` |/ _ \ | | \ / * | |_| | | | | (_| | (_) | | | / \ * \___/|_| |_|\__,_|\___/ |_| /_/\_\ * */ final JButton btnUndoTX = new JButton(SYSConst.icon22undo); btnUndoTX.setPressedIcon(SYSConst.icon22Pressed); btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT); btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnUndoTX.setContentAreaFilled(false); btnUndoTX.setBorder(null); btnUndoTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip")); btnUndoTX.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgYesNo( SYSTools.xx("misc.questions.undo1") + "<br/><i>" + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT) .format(tx.getPit()) + " " + tx.getUser().getUID() + "</i><br/>" + SYSTools.xx("misc.questions.undo2"), SYSConst.icon48undo, new Closure() { @Override public void execute(Object answer) { if (answer.equals(JOptionPane.YES_OPTION)) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); MedStock myStock = em.merge(stock); final MedStockTransaction myOldTX = em.merge(tx); myOldTX.setState(MedStockTransactionTools.STATE_CANCELLED); final MedStockTransaction myNewTX = em .merge(new MedStockTransaction(myStock, myOldTX.getAmount().negate(), MedStockTransactionTools.STATE_CANCEL_REC)); myOldTX.setText(SYSTools.xx("misc.msg.reversedBy") + ": " + DateFormat .getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT) .format(myNewTX.getPit())); myNewTX.setText(SYSTools.xx("misc.msg.reversalFor") + ": " + DateFormat .getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT) .format(myOldTX.getPit())); // myStock.getStockTransaction().add(myNewTX); // myStock.getStockTransaction().remove(tx); // myStock.getStockTransaction().add(myOldTX); em.lock(em .merge(myNewTX.getStock().getInventory().getResident()), LockModeType.OPTIMISTIC); em.lock(myStock, LockModeType.OPTIMISTIC); em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC); em.getTransaction().commit(); // synchronized (lstInventories) { // int indexInventory = lstInventories.indexOf(stock.getInventory()); // int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock); // lstInventories.get(indexInventory).getMedStocks().remove(stock); // lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock); // } // synchronized (linemap) { // linemap.remove(tx); // } createCP4(myStock.getInventory()); buildPanel(); // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { // synchronized (linemap) { // GUITools.flashBackground(linemap.get(myOldTX), Color.RED, 2); // GUITools.flashBackground(linemap.get(myNewTX), Color.YELLOW, 2); // } // } // }); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage() .indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager() .addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }); } }); btnUndoTX.setEnabled(!stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL)); pnlTitle.getRight().add(btnUndoTX); if (stock.getTradeForm().isWeightControlled() && OPDE.getAppInfo() .isAllowedTo(InternalClassACL.MANAGER, "nursingrecords.inventory")) { /*** * _ __ __ _ _ _ * ___ ___| |\ \ / /__(_) __ _| |__ | |_ * / __|/ _ \ __\ \ /\ / / _ \ |/ _` | '_ \| __| * \__ \ __/ |_ \ V V / __/ | (_| | | | | |_ * |___/\___|\__| \_/\_/ \___|_|\__, |_| |_|\__| * |___/ */ final JButton btnSetWeight = new JButton(SYSConst.icon22scales); btnSetWeight.setPressedIcon(SYSConst.icon22Pressed); btnSetWeight.setAlignmentX(Component.RIGHT_ALIGNMENT); btnSetWeight.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnSetWeight.setContentAreaFilled(false); btnSetWeight.setBorder(null); btnSetWeight.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip")); btnSetWeight.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { BigDecimal weight; new DlgYesNo(SYSConst.icon48scales, new Closure() { @Override public void execute(Object o) { if (!SYSTools.catchNull(o).isEmpty()) { BigDecimal weight = (BigDecimal) o; EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); MedStock myStock = em.merge(stock); final MedStockTransaction myTX = em.merge(tx); em.lock(myTX, LockModeType.OPTIMISTIC); myTX.setWeight(weight); em.lock(myStock, LockModeType.OPTIMISTIC); em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC); em.getTransaction().commit(); createCP4(myStock.getInventory()); buildPanel(); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager() .addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }, "nursingrecords.bhp.weight", NumberFormat.getNumberInstance().format(tx.getWeight()), new Validator<BigDecimal>() { @Override public boolean isValid(String value) { BigDecimal bd = parse(value); return bd != null && bd.compareTo(BigDecimal.ZERO) > 0; } @Override public BigDecimal parse(String text) { return SYSTools.parseDecimal(text); } }); } }); btnSetWeight.setEnabled( !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT || tx.getState() == MedStockTransactionTools.STATE_CREDIT || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL)); pnlTitle.getRight().add(btnSetWeight); } pnlTX.add(pnlTitle.getMain()); } return null; } @Override protected void done() { OPDE.getDisplayManager().setProgressBarMessage(null); OPDE.getMainframe().setBlocked(false); } }; worker.execute(); return pnlTX; }
From source file:org.ejbca.core.model.ra.raadmin.UserFullfillEndEntityProfileTest.java
/** * Test the profile fulfilling rutines//from ww w. ja va 2 s .c om * * @throws Exception error */ @Test public void testfulfillEndEntityProfiles() throws Exception { log.trace(">test01fulfillEndEntityProfiles()"); // Dummy caids final int testca2 = 3; int currentSubTest = 1; { final EndEntityProfile profile = new EndEntityProfile(); // Set so CN=modifyable required, OU0={DEP1_1,DEP1_2} required, OU1={DEP2_1,DEP2_2} required, C=OU1={SE,DK} not required profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.COUNTRY); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 0, true); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 1, true); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 0, false); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 1, false); profile.setModifyable(DnComponents.COUNTRY, 0, false); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 0, "DEP1_1;DEP1_2"); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 1, "DEP2_1;DEP2_2"); profile.setValue(DnComponents.COUNTRY, 0, "SE;DK"); profile.setValue(EndEntityProfile.AVAILCAS, 0, "" + TEST_CA_1); // Test completly erronious DN try { profile.doesUserFullfillEndEntityProfile("username", "password", "blabla", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Profile does not check DN at all."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + " = OK"); } // Test correct DN try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Profile Fulfill Test " + (currentSubTest++) + " " + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail(e.getMessage()); } // Test no username even though is required try { profile.doesUserFullfillEndEntityProfile("", "password", STANDARD_DN, "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("UserName is not checked even though it's required"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Profile Fulfill Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test no password even though is required try { profile.doesUserFullfillEndEntityProfile("username", "", STANDARD_DN, "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Password is not checked even though it's required"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Profile Test Fulfill " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test with no CN (required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "OU=DEP1_1,OU=DEP2_1,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Required CN field wasn't checked"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test with only one OU (2 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP2_1,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Required OU field wasn't checked"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test were second OU have the wrong value (Dep2_1 or Dep2_2) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP1_1,OU=DEP2_3,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error value of second OU field wasn't checked"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test without C (not required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP1_1,OU=DEP2_2", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail(e.getMessage()); } // Test illegal value of C (SE or DK) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP1_1,OU=DEP2_2, C=NO", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Inproper check of C value."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Add some subject altname fields profile.addField(DnComponents.RFC822NAME); profile.addField(DnComponents.DNSNAME); profile.addField(DnComponents.UPN); profile.addField(DnComponents.IPADDRESS); profile.setRequired(DnComponents.RFC822NAME, 0, true); profile.setRequired(DnComponents.DNSNAME, 0, true); profile.setRequired(DnComponents.UPN, 0, true); profile.setRequired(DnComponents.IPADDRESS, 0, true); profile.setModifyable(DnComponents.RFC822NAME, 0, false); profile.setModifyable(DnComponents.DNSNAME, 0, false); profile.setModifyable(DnComponents.UPN, 0, false); profile.setModifyable(DnComponents.IPADDRESS, 0, true); profile.setValue(DnComponents.RFC822NAME, 0, "test.com"); profile.setValue(DnComponents.DNSNAME, 0, "test.primekey.se"); profile.setValue(DnComponents.UPN, 0, "test.com;primekey.se"); profile.setValue(DnComponents.IPADDRESS, 0, "11.11.1.1"); profile.setRequired(EndEntityProfile.EMAIL, 0, true); profile.setModifyable(EndEntityProfile.EMAIL, 0, false); profile.setValue(EndEntityProfile.EMAIL, 0, "test.com;primekey.se"); // Test completly erronious Alt Name try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "blabla", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Profile does not check altname at all."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + " = OK"); } // Test correct Alt Name try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "RFC822NAME=test@test.com, dnsname=test.primekey.se, Upn=test@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Profile Fulfill Test " + (currentSubTest++) + " " + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail(e.getMessage()); } // Test with no RFC822NAME (required) try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "dnsname=test.primekey.se, Upn=test@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Required RFC822NAME field wasn't checked"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test with one RFC822NAME to many try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, rfc822name=test@primekey.se, dnsname=test.primekey.se, Upn=test@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("To many RFC822 names fields wasn't checked"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test that only domain is checked for RFC822name and UPN try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, dnsname=test.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Not only domains of RFC822NAME and UPN where checked: " + e.getMessage()); } // Test were DNS have illegal value try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, dnsname=test2.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error value of DNS not checked."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test without IPADDRESS (required) try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, dnsname=test.primekey.se, Upn=test12@primekey.se", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error not checking number of IPADDRESS properly."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + " = OK"); } // Test without email field (required) 1 try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, dnsname=test.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.1", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Inproper check of email field."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test without email field (required) 2 try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, dnsname=test.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.1", "", "null", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Inproper check of email field."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test without email field (required) 3 try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, dnsname=test.primekey.se, Upn=test12@primekey.se,ipaddress=11.11.1.1", "", null, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Inproper check of email field."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test illegal value of email field (test.com or primekey.se) 1 try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test11@test1.com, dnsname=test.primekey.se, Upn=test12@primekey.se,ipaddress=11.11.1.1", "", "test11@test1.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Inproper check of email field values."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER + ";" + CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA); // Test illegal value of Certificate Profile try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test11@test.com, dnsname=test.primekey.se, Upn=test12@primekey.se,ipaddress=11.11.1.1", "", "test11@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Inproper check of certificate profile values."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test Wrong CA try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test11@test.com, dnsname=test.primekey.se, Upn=test12@primekey.se,ipaddress=11.11.1.1", "", "test11@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, testca2, null); fail("Inproper check of available ca's."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " " + e.getMessage() + " = OK"); } // Test with a mix of several rfc822name fields //profile.addField(DnComponents.RFC822NAME); already set profile.addField(DnComponents.RFC822NAME); profile.addField(DnComponents.RFC822NAME); profile.addField(DnComponents.RFC822NAME); //profile.setRequired(DnComponents.RFC822NAME,0,true); already set profile.setRequired(DnComponents.RFC822NAME, 1, false); profile.setRequired(DnComponents.RFC822NAME, 2, true); profile.setRequired(DnComponents.RFC822NAME, 3, true); //profile.setUse(DnComponents.RFC822NAME, 0, true); already set profile.setUse(DnComponents.RFC822NAME, 1, false); profile.setUse(DnComponents.RFC822NAME, 2, false); profile.setUse(DnComponents.RFC822NAME, 3, false); //profile.setModifyable(DnComponents.RFC822NAME,0,false); already set profile.setModifyable(DnComponents.RFC822NAME, 1, true); profile.setModifyable(DnComponents.RFC822NAME, 2, false); profile.setModifyable(DnComponents.RFC822NAME, 3, true); //profile.setValue(DnComponents.RFC822NAME,0,"test.com"); not used profile.setValue(DnComponents.RFC822NAME, 1, "foobar.com"); profile.setValue(DnComponents.RFC822NAME, 2, "test@somefoo.com"); profile.setValue(DnComponents.RFC822NAME, 3, "somebar.com"); // Make sure normal usage works /* * Normal usage test moved down to testProfileWithRfc822Name() */ // Test missing required rfc822name field try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, rfc822name=test@somefoo.com, " + "dnsname=test.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Did not notice missing RFC822Name."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK (" + e.getMessage() + ")"); } // Try non-existing required "use end entity e-mail" try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@nodomain.com, rfc822name=test@anything.com, rfc822name=test@somefoo.com, " + "dnsname=test.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Did not check RFC822Name against e-mail field."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK (" + e.getMessage() + ")"); } // Try to ignore a required non-modifyable domain try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, rfc822name=test@anything.com, rfc822name=test@somebar.com, " + "dnsname=test.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Did not check RFC822Name against profile."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK (" + e.getMessage() + ")"); } // Use same as required non-mod field in non-req field try { profile.doesUserFullfillEndEntityProfile("username", "password", STANDARD_DN, "rfc822name=test@test.com, rfc822name=test@anything.com, rfc822name=test@somefoo.com, rfc822name=test@somefoo.com, " + "dnsname=test.primekey.se, Upn=test12@primekey.se, ipaddress=11.11.1.2", "", "test@test.com", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Did not check RFC822Name against profile." + e.getMessage()); } } {// New profile final EndEntityProfile profile = new EndEntityProfile(); // Set so CN=modifyable required, OU0={DEP1_1,DEP1_2} required, OU1={DEP2_1,DEP2_2} required, OU3=Optional, C=O{SE,DK} not required profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.COUNTRY); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 0, false); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 1, true); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 2, false); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 3, true); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 4, false); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 1, false); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 3, false); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 4, true); profile.setModifyable(DnComponents.COUNTRY, 0, false); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 1, "DEP1_1;DEP1_2"); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 3, "DEP2_1;DEP2_2"); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 4, "DEP3_1;DEP3_2"); profile.setValue(DnComponents.COUNTRY, 0, "SE;DK"); profile.setValue(EndEntityProfile.AVAILCAS, 0, "" + TEST_CA_1); // Test with two OU (2 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=,OU=DEP1_1,OU=,OU=DEP2_2,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Required OU fields wasn't checked propertly: " + e.getMessage()); } // Test with tree OU (2 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=,OU=DEP1_1,OU=,OU=DEP2_2,OU=DEP3_3,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Required OU fields wasn't checked propertly: " + e.getMessage()); } profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 4, false); // Test with tree OU (2 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=,OU=DEP1_1,OU=,OU=DEP2_2,OU=DEP3_1,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Required OU fields wasn't checked propertly: " + e.getMessage()); } // Test with tree OU (2 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=,OU=DEP1_1,OU=,OU=DEP2_2,OU=DEP3_3,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Required OU fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } } { // Test Reverse Checks // New profile final EndEntityProfile profile = new EndEntityProfile(); profile.setReverseFieldChecks(true); // Set so CN=modifyable required, OU0=Modifyable not required, OU1=Modifyable not required, OU3=required {hard,soft}, C=O{SE,DK} not required profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.ORGANIZATIONALUNIT); profile.addField(DnComponents.COUNTRY); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 0, false); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 1, false); profile.setRequired(DnComponents.ORGANIZATIONALUNIT, 2, true); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 0, true); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 1, true); profile.setModifyable(DnComponents.ORGANIZATIONALUNIT, 2, false); profile.setModifyable(DnComponents.COUNTRY, 0, false); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 0, ""); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 1, ""); profile.setValue(DnComponents.ORGANIZATIONALUNIT, 2, "HARD;SOFT"); profile.setValue(DnComponents.COUNTRY, 0, "SE;DK"); profile.setValue(EndEntityProfile.AVAILCAS, 0, "" + TEST_CA_1); // Test with one OU (1 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse OU fields wasn't checked propertly: " + e.getMessage()); } // Test with two OU (1 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP2_1,OU=HARD,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse OU fields wasn't checked propertly: " + e.getMessage()); } // Test with three OU (1 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP1_1,OU=DEP2_1,OU=HARD,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse OU fields wasn't checked propertly: " + e.getMessage()); } // Test with four OU (3 allowed) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP0_1,OU=DEP1_1,OU=DEP2_1,OU=HARD,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse OU fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test with wrong data in nonmodifiable field try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP1_1,OU=DEP2_1,OU=HARD2,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse OU fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test that the right data is checked when a lesser number of field is used try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse OU fields wasn't checked propertly: " + e.getMessage()); } // Test with wrong data in nonmodifiable field when having only one ou try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD2,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse OU fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test with no ou try { profile.doesUserFullfillEndEntityProfile("username", "passworCerd", "CN=John Smith,C=SE", "null", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse OU fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test Reverse checks of subject alt names // Set so CN=modifyable required, OU=Modifyable not required, OU1=Modifyable not required, OU3=required {hard,soft}, C=O{SE,DK} not required profile.addField(DnComponents.IPADDRESS); profile.addField(DnComponents.IPADDRESS); profile.addField(DnComponents.IPADDRESS); profile.addField(DnComponents.DNSNAME); profile.setRequired(DnComponents.IPADDRESS, 0, false); profile.setRequired(DnComponents.IPADDRESS, 1, false); profile.setRequired(DnComponents.IPADDRESS, 2, true); profile.setModifyable(DnComponents.IPADDRESS, 0, true); profile.setModifyable(DnComponents.IPADDRESS, 1, true); profile.setModifyable(DnComponents.IPADDRESS, 2, false); profile.setModifyable(DnComponents.DNSNAME, 0, false); profile.setValue(DnComponents.IPADDRESS, 0, ""); profile.setValue(DnComponents.IPADDRESS, 1, ""); profile.setValue(DnComponents.IPADDRESS, 2, "10.1.1.1;10.2.2.2"); profile.setValue(DnComponents.DNSNAME, 0, "test1.se;test2.se"); // Test with one IPAddress (1 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse IPADDRESS fields wasn't checked propertly: " + e.getMessage()); } // Test with two IPAddress (1 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP2_1,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=11.1.1.1,ipaddress=10.1.1.1", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse IPADDRESS fields wasn't checked propertly: " + e.getMessage()); } // Test with three IPAddress (1 required) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP1_1,OU=DEP2_1,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=12.1.1.1,ipaddress=11.1.1.1,ipaddress=10.1.1.1", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse IPADDRESS fields wasn't checked propertly: " + e.getMessage()); } // Test with four IPAddress (3 allowed) try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP0_1,OU=DEP1_1,OU=DEP2_1,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=12.1.1.1,ipaddress=12.1.1.1,ipaddress=11.1.1.1,ipaddress=10.1.1.1", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse IPADDRESS fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test with wrong data in nonmodifiable field try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=DEP1_1,OU=DEP2_1,OU=HARD2,C=SE", "dnsname=test1.se,ipaddress=12.1.1.1,ipaddress=11.1.1.1,ipaddress=10.1.1.2", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse IPADDRESS fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test that the right data is checked when a lesser number of field is used try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Reverse IPADDRESS fields wasn't checked propertly: " + e.getMessage()); } // Test with wrong data in nonmodifiable field when having only one ou try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD2,C=SE", "dnsname=test1.se,ipaddress=11.1.1.1", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse IPADDRESS fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test with no ou try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,C=SE", "dnsname=test1.se", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error Reverse IPADDRESS fields wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Test adding required fields for Subject Directory Attributes // Set so CN=modifyable required, OU=Modifyable not required, OU1=Modifyable not required, OU3=required {hard,soft}, C=O{SE,DK} not required profile.addField(DnComponents.DATEOFBIRTH); profile.addField(DnComponents.PLACEOFBIRTH); profile.addField(DnComponents.GENDER); profile.addField(DnComponents.COUNTRYOFCITIZENSHIP); profile.addField(DnComponents.COUNTRYOFRESIDENCE); profile.setRequired(DnComponents.DATEOFBIRTH, 0, false); profile.setRequired(DnComponents.PLACEOFBIRTH, 0, false); profile.setRequired(DnComponents.GENDER, 0, false); profile.setRequired(DnComponents.COUNTRYOFCITIZENSHIP, 0, false); profile.setRequired(DnComponents.COUNTRYOFRESIDENCE, 0, false); profile.setModifyable(DnComponents.DATEOFBIRTH, 0, true); profile.setModifyable(DnComponents.PLACEOFBIRTH, 0, true); profile.setModifyable(DnComponents.GENDER, 0, true); profile.setModifyable(DnComponents.COUNTRYOFCITIZENSHIP, 0, true); profile.setModifyable(DnComponents.COUNTRYOFRESIDENCE, 0, false); profile.setValue(DnComponents.DATEOFBIRTH, 0, ""); profile.setValue(DnComponents.PLACEOFBIRTH, 0, ""); profile.setValue(DnComponents.GENDER, 0, ""); profile.setValue(DnComponents.COUNTRYOFCITIZENSHIP, 0, ""); profile.setValue(DnComponents.COUNTRYOFRESIDENCE, 0, "SE"); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "CountryOfCitizenship=FOO", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error CountryOfCitizenship wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { assertEquals("Invalid COUNTRYOFCITIZENSHIP. Must be of length two.", e.getMessage()); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "CountryOfCitizenship=SE, CountryOfResidence=Foo", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error CountryOfCitizenship wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { assertEquals("Invalid COUNTRYOFRESIDENCE. Must be of length two.", e.getMessage()); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "CountryOfCitizenship=SE, CountryOfResidence=TR", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error CountryOfCitizenship wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { assertEquals("Field COUNTRYOFRESIDENCE data didn't match requirement of end entity profile.", e.getMessage()); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "CountryOfCitizenship=SE, CountryOfResidence=SE, Gender=M, PlaceOfBirth=Stockholm", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error Subject Dir Attributes wasn't checked propertly"); } try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "DateOfBirth=189901, CountryOfCitizenship=SE, CountryOfResidence=SE", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error DateOfBirth wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { assertEquals("Invalid DATEOFBIRTH. Must be of length eight.", e.getMessage()); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "DateOfBirth=189901AA, CountryOfCitizenship=SE, CountryOfResidence=SE", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); fail("Error DateOfBirth wasn't checked propertly"); } catch (UserDoesntFullfillEndEntityProfile e) { assertEquals("Invalid DATEOFBIRTH. Must be only numbers.", e.getMessage()); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith,OU=HARD,C=SE", "dnsname=test1.se,ipaddress=10.1.1.1", "DateOfBirth=18990101, CountryOfCitizenship=SE, CountryOfResidence=SE", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, null); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error DateOfBirth wasn't checked propertly"); } } { // Test time constraints final EndEntityProfile profile = new EndEntityProfile(); Date now = new Date(); Date endOfTime = new Date(Long.MAX_VALUE); FastDateFormat sm = FastDateFormat.getInstance("yyyy-MM-dd HH:mm"); String staticNow = sm.format(now); String relativeNow = "0:00:00"; String staticEndOfTime = sm.format(endOfTime); String relativeEndOfTime = "33000:00:00"; // ~100 years String staticInvalid = "XXXX-XX-XX XX:XX PM"; String relativeInvalid = "XXXXX:XXX:XXX"; String relativeNegative = "-10:00:00"; ExtendedInformation ei = new ExtendedInformation(); // Use empty, should fail profile.setValue(EndEntityProfile.AVAILCAS, 0, "" + TEST_CA_1); profile.setUse(EndEntityProfile.STARTTIME, 0, true); profile.setUse(EndEntityProfile.ENDTIME, 0, false); profile.setValue(EndEntityProfile.STARTTIME, 0, ""); profile.setValue(EndEntityProfile.ENDTIME, 0, ""); ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, ""); try { // Custom starttime can be empty or null profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Empty start time was not checked correctly."); } profile.setUse(EndEntityProfile.STARTTIME, 0, false); profile.setUse(EndEntityProfile.ENDTIME, 0, true); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, ""); try { // Custom endtime can be empty or null profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Empty end time was not checked correctly."); } // Static times work? profile.setUse(EndEntityProfile.STARTTIME, 0, true); profile.setUse(EndEntityProfile.ENDTIME, 0, true); ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, staticNow); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticEndOfTime); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Static times does not work. (" + e.getMessage() + ")"); } // Relative times work? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, relativeNow); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, relativeEndOfTime); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Relative times does not work."); } // Static start, rel end work? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, staticNow); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, relativeEndOfTime); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Static start time w relative end time does not work."); } // Rel start, static end work? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, relativeNow); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticEndOfTime); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Relative start time w static end time does not work."); } // Negative relative start times work? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, relativeNegative); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticEndOfTime); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Possible to use negative start time."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Negative relative end times work? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, staticNow); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, relativeNegative); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Possible to use negative end time."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Static end before start ok? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, staticEndOfTime); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticNow); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Static end time before static start time allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Relative end before start ok? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, relativeEndOfTime); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, relativeNow); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Relative end time before relative start time allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Invalid static start ok? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, staticInvalid); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticEndOfTime); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Invalid static start time allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Invalid static end ok? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, staticNow); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticInvalid); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Invalid static start time allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Invalid relative start ok? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, relativeInvalid); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticEndOfTime); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Invalid relative start time allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Invalid relative end ok? ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, relativeNow); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, staticInvalid); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Invalid relative start time allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } // Is this Java-version parsing dates correctly? long magicDateTime = 1181040300000L; // "12:45 PM" in US Locale String value1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US) .format(new Date(magicDateTime)); String value2 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US).format( DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US).parse(value1)); long magicDateTime2 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US) .parse(value2).getTime(); if (magicDateTime != magicDateTime2) { fail("Error: Java does not parse dates correctly. " + magicDateTime + " " + magicDateTime2 + " " + value1 + " " + value2); } } { // Test allow multiple requests final EndEntityProfile profile = new EndEntityProfile(); final ExtendedInformation ei = new ExtendedInformation(); // Use empty, should fail profile.setValue(EndEntityProfile.AVAILCAS, 0, "" + TEST_CA_1); profile.setUse(EndEntityProfile.ALLOWEDREQUESTS, 0, false); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Allowedrequests not checked correctly, should be allowed."); } ei.setCustomData(ExtendedInformationFields.CUSTOM_REQUESTCOUNTER, "2"); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: Allowed requests was not checked correctly, should not be allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } profile.setUse(EndEntityProfile.ALLOWEDREQUESTS, 0, true); try { profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); log.debug("End Entity Fulfill Profile Test " + (currentSubTest++) + " = OK"); } catch (UserDoesntFullfillEndEntityProfile e) { fail("Error: Allowedrequests not checked correctly, should be allowed."); } } { // New profile final EndEntityProfile profile = new EndEntityProfile(); // Set so maxFailedLogins=non-modifyable required profile.addField(EndEntityProfile.MAXFAILEDLOGINS); profile.setUse(EndEntityProfile.MAXFAILEDLOGINS, 0, true); profile.setRequired(EndEntityProfile.MAXFAILEDLOGINS, 0, true); profile.setModifyable(EndEntityProfile.MAXFAILEDLOGINS, 0, false); profile.setValue(EndEntityProfile.MAXFAILEDLOGINS, 0, "7"); profile.setValue(EndEntityProfile.AVAILCAS, 0, "" + TEST_CA_1); try { final ExtendedInformation ei = new ExtendedInformation(); ei.setMaxLoginAttempts(1234); profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); fail("Error: maxFailedLogins was not checked correctly, should not be allowed."); } catch (UserDoesntFullfillEndEntityProfile e) { // OK } try { final ExtendedInformation ei = new ExtendedInformation(); ei.setMaxLoginAttempts(7); profile.doesUserFullfillEndEntityProfile("username", "password", "CN=John Smith", "", "", "", CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, false, false, false, SecConst.TOKEN_SOFT_BROWSERGEN, 0, TEST_CA_1, ei); } catch (UserDoesntFullfillEndEntityProfile e) { log.error(e.getMessage(), e); fail("Error: maxFailedLogins was not checked correctly, should be allowed."); } log.trace("<test01fulfillEndEntityProfiles()"); } }
From source file:org.methodize.nntprss.admin.AdminServlet.java
private void cmdShowCurrentChannels(HttpServletResponse response) throws ServletException, IOException { DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); Writer writer = response.getWriter(); writeHeader(writer, TAB_VIEW_CHANNELS); writeCheckboxSelector(writer, "checkAllChannels", "chl", "channels"); writer.write("<form name='channels' action='/?action=channelaction' method='POST'>"); writer.write("<table class='tableborder' border='0'>"); writer.write("<tr><th colspan='5' class='tableHead'>Channels</td></th>"); // writer.write("<tr><th class='subHead'><input type='checkbox' name='change' onClick='checkAllChannels(this);'></th><th class='subHead'>Newsgroup Name</th><th class='subHead'>RSS URL</th><th class='subHead'>Last Polled</th></tr>"); writer.write(//from w w w . j a v a 2 s .c o m "<tr><th class='subHead'><input type='checkbox' name='change' onClick='checkAllChannels(this);'></th><th class='subHead'>Newsgroup Name</th><th class='subHead'> </th><th class='subHead'>Feed URL</th><th class='subHead'>Last Polled</th></tr>"); ChannelManager channelManager = (ChannelManager) getServletContext() .getAttribute(AdminServer.SERVLET_CTX_RSS_MANAGER); NNTPServer nntpServer = (NNTPServer) getServletContext().getAttribute(AdminServer.SERVLET_CTX_NNTP_SERVER); Iterator channelIter = channelManager.channels(); String newsPrefix = getNewsURLPrefix(nntpServer); while (channelIter.hasNext()) { Channel channel = (Channel) channelIter.next(); writer.write("<tr><td class='row1'><input type='checkbox' name='chl" + HTMLHelper.escapeString(channel.getName()) + "'></td>"); // Truncate displayed URL... String url = channel.getUrl(); if (url.length() > 32) { url = url.substring(0, 32) + "..."; } String lastPolled; if (channel.getLastPolled() != null) { lastPolled = df.format(channel.getLastPolled()); } else { lastPolled = "Awaiting poll"; } String parser = (channel.isParseAtAllCost() ? "*" : ""); switch (channel.getStatus()) { case Channel.STATUS_INVALID_CONTENT: case Channel.STATUS_NOT_FOUND: case Channel.STATUS_UNKNOWN_HOST: case Channel.STATUS_NO_ROUTE_TO_HOST: case Channel.STATUS_PROXY_AUTHENTICATION_REQUIRED: case Channel.STATUS_USER_AUTHENTICATION_REQUIRED: writer.write("<td class='chlerror' bgcolor='#FF0000'>" + parser + "<a class='row' title='Channel configuration' href='/?action=show&name=" + URLEncoder.encode(channel.getName()) + "'><font color='#FFFFFF'>" + channel.getName() + "</font></a></td>"); writer.write( "<td class='chlerror' bgcolor='#FF0000'><a class='row' title='Read this channel in your default newsreader' href='" + newsPrefix + HTMLHelper.escapeString(channel.getName()) + "'><font color='#FFFFFF'>[Read]</font></a></td>"); writer.write( "<td class='chlerror' bgcolor='#FF0000'><font color='#FFFFFF'>" + url + "</font></td>"); writer.write("<td class='chlerror' bgcolor='#FF0000'><font color='#FFFFFF'>" + lastPolled + "</font></td></tr>"); break; case Channel.STATUS_SOCKET_EXCEPTION: case Channel.STATUS_CONNECTION_TIMEOUT: writer.write("<td class='chlwarning' bgcolor='#FFFF00'>" + parser + "<a class='row' title='Channel configuration' href='/?action=show&name=" + URLEncoder.encode(channel.getName()) + "'><font color='#000000'>" + channel.getName() + "</font></a></td>"); writer.write( "<td class='chlwarning' bgcolor='#FFFF00'><a class='row' title='Read this channel in your default newsreader' href='" + newsPrefix + HTMLHelper.escapeString(channel.getName()) + "'>[Read]</a></td>"); writer.write( "<td class='chlwarning' bgcolor='#FFFF00'><font color='#000000'>" + url + "</font></td>"); writer.write("<td class='chlwarning' bgcolor='#FFFF00'><font color='#000000'>" + lastPolled + "</font></td></tr>"); break; default: if (channel.isEnabled()) { writer.write("<td class='row1'>" + parser + "<a class='row' title='Channel configuration' href='/?action=show&name=" + URLEncoder.encode(channel.getName()) + "'>" + channel.getName() + "</a></td>"); writer.write( "<td class='row1'><a class='row' title='Read this channel in your default newsreader' href='" + newsPrefix + HTMLHelper.escapeString(channel.getName()) + "'>[Read]</a></td>"); writer.write("<td class='row1'>" + url + "</td>"); writer.write("<td class='row1'>" + lastPolled + "</td></tr>"); } else { writer.write("<td class='chldisabled' bgcolor='#CCCCCC'>" + parser + "<a class='row' title='Channel configuration' href='/?action=show&name=" + URLEncoder.encode(channel.getName()) + "'>" + channel.getName() + "</a></td>"); writer.write( "<td class='chldisabled'><a class='row' title='Read this channel in your default newsreader' href='" + newsPrefix + HTMLHelper.escapeString(channel.getName()) + "'>[Read]</a></td>"); writer.write("<td class='chldisabled' bgcolor='#CCCCCC'>" + url + "</td>"); writer.write("<td class='chldisabled' bgcolor='#CCCCCC'>" + lastPolled + "</td></tr>"); } } } writer.write("<tr><td class='row2' colspan='5'>"); writer.write( "<input type='submit' onClick='return confirm(\"Are you sure you want to delete these channels?\");' name='delete' value='Delete Selected Channels'> " + "<input type='submit' onClick='return confirm(\"Are you sure you want to repoll these channels?\");' name='repoll' value='Repoll Selected Channels'>" + "</td></tr>"); writer.write("</table><font size='-1'>[* = Channel configured for Parse-At-All-Cost parser]</font><p>"); writer.write("</form><p>"); writeFooter(writer); writer.flush(); }
From source file:net.massbank.validator.RecordValidator.java
/** * ??// w ww . j a v a2 s .c om * * @param db * DB * @param op * PrintWriter? * @param dataPath * ? * @param registPath * * @param ver * ? * @return ??Map<??, ?> * @throws IOException * */ private static TreeMap<String, String> validationRecordOnline(DatabaseAccess db, PrintStream op, String dataPath, String registPath, int ver) throws IOException { op.println(msgInfo("validation archive is [" + UPLOAD_RECDATA_ZIP + "] or [" + UPLOAD_RECDATA_MSBK + "].")); if (ver == 1) { op.println(msgInfo("check record format version is [version 1].")); } final String[] dataList = (new File(dataPath)).list(); TreeMap<String, String> validationMap = new TreeMap<String, String>(); if (dataList.length == 0) { op.println(msgWarn("no file for validation.")); return validationMap; } // ---------------------------------------------------- // ??? // ---------------------------------------------------- String[] requiredList = new String[] { // Ver.2 "ACCESSION: ", "RECORD_TITLE: ", "DATE: ", "AUTHORS: ", "LICENSE: ", "CH$NAME: ", "CH$COMPOUND_CLASS: ", "CH$FORMULA: ", "CH$EXACT_MASS: ", "CH$SMILES: ", "CH$IUPAC: ", "AC$INSTRUMENT: ", "AC$INSTRUMENT_TYPE: ", "AC$MASS_SPECTROMETRY: MS_TYPE ", "AC$MASS_SPECTROMETRY: ION_MODE ", "PK$NUM_PEAK: ", "PK$PEAK: " }; if (ver == 1) { // Ver.1 requiredList = new String[] { "ACCESSION: ", "RECORD_TITLE: ", "DATE: ", "AUTHORS: ", "COPYRIGHT: ", "CH$NAME: ", "CH$COMPOUND_CLASS: ", "CH$FORMULA: ", "CH$EXACT_MASS: ", "CH$SMILES: ", "CH$IUPAC: ", "AC$INSTRUMENT: ", "AC$INSTRUMENT_TYPE: ", "AC$ANALYTICAL_CONDITION: MODE ", "PK$NUM_PEAK: ", "PK$PEAK: " }; } for (int i = 0; i < dataList.length; i++) { String name = dataList[i]; String status = ""; StringBuilder detailsErr = new StringBuilder(); StringBuilder detailsWarn = new StringBuilder(); // ???? File file = new File(dataPath + name); if (file.isDirectory()) { // ?? status = STATUS_ERR; detailsErr.append("[" + name + "] is directory."); validationMap.put(name, status + "\t" + detailsErr.toString()); continue; } else if (file.isHidden()) { // ??? status = STATUS_ERR; detailsErr.append("[" + name + "] is hidden."); validationMap.put(name, status + "\t" + detailsErr.toString()); continue; } else if (name.lastIndexOf(REC_EXTENSION) == -1) { // ???? status = STATUS_ERR; detailsErr.append("file extension of [" + name + "] is not [" + REC_EXTENSION + "]."); validationMap.put(name, status + "\t" + detailsErr.toString()); continue; } // ?? boolean isEndTagRead = false; boolean isInvalidInfo = false; boolean isDoubleByte = false; ArrayList<String> fileContents = new ArrayList<String>(); boolean existLicense = false; // LICENSE?Ver.1 ArrayList<String> workChName = new ArrayList<String>(); // RECORD_TITLE??CH$NAME??Ver.1? String workAcInstrumentType = ""; // RECORD_TITLE??AC$INSTRUMENT_TYPE??Ver.1? String workAcMsType = ""; // RECORD_TITLE??AC$MASS_SPECTROMETRY: // MS_TYPE??Ver.2 String line = ""; BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { if (isEndTagRead) { if (!line.equals("")) { isInvalidInfo = true; } } // if (line.startsWith("//")) { isEndTagRead = true; } fileContents.add(line); // LICENSE?Ver.1 if (line.startsWith("LICENSE: ")) { existLicense = true; } // CH$NAME?Ver.1? else if (line.startsWith("CH$NAME: ")) { workChName.add(line.trim().replaceAll("CH\\$NAME: ", "")); } // AC$INSTRUMENT_TYPE?Ver.1? else if (line.startsWith("AC$INSTRUMENT_TYPE: ")) { workAcInstrumentType = line.trim().replaceAll("AC\\$INSTRUMENT_TYPE: ", ""); } // AC$MASS_SPECTROMETRY: MS_TYPE?Ver.2 else if (ver != 1 && line.startsWith("AC$MASS_SPECTROMETRY: MS_TYPE ")) { workAcMsType = line.trim().replaceAll("AC\\$MASS_SPECTROMETRY: MS_TYPE ", ""); } // ? if (!isDoubleByte) { byte[] bytes = line.getBytes("MS932"); if (bytes.length != line.length()) { isDoubleByte = true; } } } } catch (IOException e) { Logger.getLogger("global").severe("file read failed." + NEW_LINE + " " + file.getPath()); e.printStackTrace(); op.println(msgErr("server error.")); validationMap.clear(); return validationMap; } finally { try { if (br != null) { br.close(); } } catch (IOException e) { } } if (isInvalidInfo) { // ????? if (status.equals("")) status = STATUS_WARN; detailsWarn.append("invalid after the end tag [//]."); } if (isDoubleByte) { // ????? if (status.equals("")) status = STATUS_ERR; detailsErr.append("double-byte character included."); } if (ver == 1 && existLicense) { // LICENSE???Ver.1 if (status.equals("")) status = STATUS_ERR; detailsErr.append("[LICENSE: ] tag can not be used in record format [version 1]."); } // ---------------------------------------------------- // ???? // ---------------------------------------------------- boolean isNameCheck = false; int peakNum = -1; for (int j = 0; j < requiredList.length; j++) { String requiredStr = requiredList[j]; ArrayList<String> valStrs = new ArrayList<String>(); // boolean findRequired = false; // boolean findValue = false; // boolean isPeakMode = false; // for (int k = 0; k < fileContents.size(); k++) { String lineStr = fileContents.get(k); // ????RELATED_RECORD?????? if (lineStr.startsWith("//")) { // Ver.1? break; } else if (ver == 1 && lineStr.startsWith("RELATED_RECORD:")) { // Ver.1 break; } // ????? else if (isPeakMode) { findRequired = true; if (!lineStr.trim().equals("")) { valStrs.add(lineStr); } } // ?????? else if (lineStr.indexOf(requiredStr) != -1) { // findRequired = true; if (requiredStr.equals("PK$PEAK: ")) { isPeakMode = true; findValue = true; valStrs.add(lineStr.replace(requiredStr, "")); } else { // String tmpVal = lineStr.replace(requiredStr, ""); if (!tmpVal.trim().equals("")) { findValue = true; valStrs.add(tmpVal); } break; } } } if (!findRequired) { // ?????? status = STATUS_ERR; detailsErr.append("no required item [" + requiredStr + "]."); } else { if (!findValue) { // ????? status = STATUS_ERR; detailsErr.append("no value of required item [" + requiredStr + "]."); } else { // ??? // ---------------------------------------------------- // ?? // ---------------------------------------------------- String val = (valStrs.size() > 0) ? valStrs.get(0) : ""; // ACESSIONVer.1? if (requiredStr.equals("ACCESSION: ")) { if (!val.equals(name.replace(REC_EXTENSION, ""))) { status = STATUS_ERR; detailsErr.append("value of required item [" + requiredStr + "] not correspond to file name."); } if (val.length() != 8) { status = STATUS_ERR; detailsErr.append( "value of required item [" + requiredStr + "] is 8 digits necessary."); } } // RECORD_TITLEVer.1? else if (requiredStr.equals("RECORD_TITLE: ")) { if (!val.equals(DEFAULT_VALUE)) { if (val.indexOf(";") != -1) { String[] recTitle = val.split(";"); if (!workChName.contains(recTitle[0].trim())) { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "], compound name is not included in the [CH$NAME]."); } if (!workAcInstrumentType.equals(recTitle[1].trim())) { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "], instrument type is different from [AC$INSTRUMENT_TYPE]."); } if (ver != 1 && !workAcMsType.equals(recTitle[2].trim())) { // Ver.2 if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "], ms type is different from [AC$MASS_SPECTROMETRY: MS_TYPE]."); } } else { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "] is not record title format."); if (!workChName.contains(val)) { detailsWarn.append("value of required item [" + requiredStr + "], compound name is not included in the [CH$NAME]."); } if (!workAcInstrumentType.equals(DEFAULT_VALUE)) { detailsWarn.append("value of required item [" + requiredStr + "], instrument type is different from [AC$INSTRUMENT_TYPE]."); } if (ver != 1 && !workAcMsType.equals(DEFAULT_VALUE)) { // Ver.2 detailsWarn.append("value of required item [" + requiredStr + "], ms type is different from [AC$MASS_SPECTROMETRY: MS_TYPE]."); } } } else { if (!workAcInstrumentType.equals(DEFAULT_VALUE)) { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "], instrument type is different from [AC$INSTRUMENT_TYPE]."); } if (ver != 1 && !workAcMsType.equals(DEFAULT_VALUE)) { // Ver.2 if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "], ms type is different from [AC$MASS_SPECTROMETRY: MS_TYPE]."); } } } // DATEVer.1? else if (requiredStr.equals("DATE: ") && !val.equals(DEFAULT_VALUE)) { val = val.replace(".", "/"); val = val.replace("-", "/"); try { DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN).parse(val); } catch (ParseException e) { if (status.equals("")) status = STATUS_WARN; detailsWarn .append("value of required item [" + requiredStr + "] is not date format."); } } // CH$COMPOUND_CLASSVer.1? else if (requiredStr.equals("CH$COMPOUND_CLASS: ") && !val.equals(DEFAULT_VALUE)) { if (!val.startsWith("Natural Product") && !val.startsWith("Non-Natural Product")) { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "] is not compound class format."); } } // CH$EXACT_MASSVer.1? else if (requiredStr.equals("CH$EXACT_MASS: ") && !val.equals(DEFAULT_VALUE)) { try { Double.parseDouble(val); } catch (NumberFormatException e) { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "] is not numeric."); } } // AC$INSTRUMENT_TYPEVer.1? else if (requiredStr.equals("AC$INSTRUMENT_TYPE: ") && !val.equals(DEFAULT_VALUE)) { if (val.trim().indexOf(" ") != -1) { if (status.equals("")) status = STATUS_WARN; detailsWarn .append("value of required item [" + requiredStr + "] is space included."); } if (val.trim().indexOf(" ") != -1) { if (status.equals("")) status = STATUS_WARN; detailsWarn .append("value of required item [" + requiredStr + "] is space included."); } } // AC$MASS_SPECTROMETRY: MS_TYPEVer.2 else if (ver != 1 && requiredStr.equals("AC$MASS_SPECTROMETRY: MS_TYPE ") && !val.equals(DEFAULT_VALUE)) { boolean isMsType = true; if (val.startsWith("MS")) { val = val.replace("MS", ""); if (!val.equals("")) { try { Integer.parseInt(val); } catch (NumberFormatException e) { isMsType = false; } } } else { isMsType = false; } if (!isMsType) { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "] is not \"MSn\"."); } } // AC$MASS_SPECTROMETRY: // ION_MODEVer.2?AC$ANALYTICAL_CONDITION: MODEVer.1 else if ((ver != 1 && requiredStr.equals("AC$MASS_SPECTROMETRY: ION_MODE ") && !val.equals(DEFAULT_VALUE)) || (ver == 1 && requiredStr.equals("AC$ANALYTICAL_CONDITION: MODE ") && !val.equals(DEFAULT_VALUE))) { if (!val.equals("POSITIVE") && !val.equals("NEGATIVE")) { if (status.equals("")) status = STATUS_WARN; detailsWarn.append("value of required item [" + requiredStr + "] is not \"POSITIVE\" or \"NEGATIVE\"."); } } // PK$NUM_PEAKVer.1? else if (requiredStr.equals("PK$NUM_PEAK: ") && !val.equals(DEFAULT_VALUE)) { try { peakNum = Integer.parseInt(val); } catch (NumberFormatException e) { status = STATUS_ERR; detailsErr.append("value of required item [" + requiredStr + "] is not numeric."); } } // PK$PEAK:Ver.1? else if (requiredStr.equals("PK$PEAK: ")) { if (valStrs.size() == 0 || !valStrs.get(0).startsWith("m/z int. rel.int.")) { status = STATUS_ERR; detailsErr.append( "value of required item [PK$PEAK: ] , the first line is not \"PK$PEAK: m/z int. rel.int.\"."); } else { boolean isNa = false; String peak = ""; String mz = ""; String intensity = ""; boolean mzDuplication = false; boolean mzNotNumeric = false; boolean intensityNotNumeric = false; boolean invalidFormat = false; HashSet<String> mzSet = new HashSet<String>(); for (int l = 0; l < valStrs.size(); l++) { peak = valStrs.get(l).trim(); // N/A if (peak.indexOf(DEFAULT_VALUE) != -1) { isNa = true; break; } if (l == 0) { continue; } // m/z int. rel.int.?????????? if (peak.indexOf(" ") != -1) { mz = peak.split(" ")[0]; if (!mzSet.add(mz)) { mzDuplication = true; } try { Double.parseDouble(mz); } catch (NumberFormatException e) { mzNotNumeric = true; } intensity = peak.split(" ")[1]; try { Double.parseDouble(intensity); } catch (NumberFormatException e) { intensityNotNumeric = true; } } else { invalidFormat = true; } if (mzDuplication && mzNotNumeric && intensityNotNumeric && invalidFormat) { break; } } if (isNa) {// PK$PEAK:?N/A?? if (peakNum != -1) { // PK$NUM_PEAK:N/A?? if (status.equals("")) status = STATUS_WARN; detailsWarn .append("value of required item [PK$NUM_PEAK: ] is mismatch or \"" + DEFAULT_VALUE + "\"."); } if (valStrs.size() - 1 > 0) { // PK$PEAK:???????? if (status.equals("")) status = STATUS_WARN; detailsWarn.append( "value of required item [PK$NUM_PEAK: ] is invalid peak information exists."); } } else { if (mzDuplication) { status = STATUS_ERR; detailsErr.append( "mz value of required item [" + requiredStr + "] is duplication."); } if (mzNotNumeric) { status = STATUS_ERR; detailsErr.append( "mz value of required item [" + requiredStr + "] is not numeric."); } if (intensityNotNumeric) { status = STATUS_ERR; detailsErr.append("intensity value of required item [" + requiredStr + "] is not numeric."); } if (invalidFormat) { status = STATUS_ERR; detailsErr.append( "value of required item [" + requiredStr + "] is not peak format."); } if (peakNum != 0 && valStrs.size() - 1 == 0) { // ?????N/A????PK$NUM_PEAK:?0??????? if (status.equals("")) status = STATUS_WARN; detailsWarn.append( "value of required item [PK$PEAK: ] is no value. at that time, please add \"" + DEFAULT_VALUE + "\". "); } if (peakNum != valStrs.size() - 1) { if (status.equals("")) status = STATUS_WARN; detailsWarn .append("value of required item [PK$NUM_PEAK: ] is mismatch or \"" + DEFAULT_VALUE + "\"."); } } } } } } } String details = detailsErr.toString() + detailsWarn.toString(); if (status.equals("")) { status = STATUS_OK; details = " "; } validationMap.put(name, status + "\t" + details); } // ---------------------------------------------------- // ???? // ---------------------------------------------------- // ?ID?DB HashSet<String> regIdList = new HashSet<String>(); String[] sqls = { "SELECT ID FROM SPECTRUM ORDER BY ID", "SELECT ID FROM RECORD ORDER BY ID", "SELECT ID FROM PEAK GROUP BY ID ORDER BY ID", "SELECT ID FROM CH_NAME ID ORDER BY ID", "SELECT ID FROM CH_LINK ID ORDER BY ID", "SELECT ID FROM TREE WHERE ID IS NOT NULL AND ID<>'' ORDER BY ID" }; for (int i = 0; i < sqls.length; i++) { String execSql = sqls[i]; ResultSet rs = null; try { rs = db.executeQuery(execSql); while (rs.next()) { String idStr = rs.getString("ID"); regIdList.add(idStr); } } catch (SQLException e) { Logger.getLogger("global").severe(" sql : " + execSql); e.printStackTrace(); op.println(msgErr("database access error.")); return new TreeMap<String, String>(); } finally { try { if (rs != null) { rs.close(); } } catch (SQLException e) { } } } // ?ID? final String[] recFileList = (new File(registPath)).list(); for (int i = 0; i < recFileList.length; i++) { String name = recFileList[i]; File file = new File(registPath + File.separator + name); if (!file.isFile() || file.isHidden() || name.lastIndexOf(REC_EXTENSION) == -1) { continue; } String idStr = name.replace(REC_EXTENSION, ""); regIdList.add(idStr); } // ?? for (Map.Entry<String, String> e : validationMap.entrySet()) { String statusStr = e.getValue().split("\t")[0]; if (statusStr.equals(STATUS_ERR)) { continue; } String nameStr = e.getKey(); String idStr = e.getKey().replace(REC_EXTENSION, ""); String detailsStr = e.getValue().split("\t")[1]; if (regIdList.contains(idStr)) { statusStr = STATUS_WARN; detailsStr += "id [" + idStr + "] of file name [" + nameStr + "] already registered."; validationMap.put(nameStr, statusStr + "\t" + detailsStr); } } return validationMap; }
From source file:op.care.reports.PnlReport.java
private JPanel getMenu(final NReport nreport) { JPanel pnlMenu = new JPanel(new VerticalLayout()); if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) { /***/* www . j a v a2s . co m*/ * _____ _ _ _ * | ____|__| (_) |_ * | _| / _` | | __| * | |__| (_| | | |_ * |_____\__,_|_|\__| * */ final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.reports.btnEdit.tooltip", SYSConst.icon22edit3, null); btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgReport(nreport.clone(), new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); final NReport newReport = em.merge((NReport) o); NReport oldReport = em.merge(nreport); em.lock(oldReport, LockModeType.OPTIMISTIC); newReport.setReplacementFor(oldReport); for (SYSNR2FILE oldAssignment : oldReport.getAttachedFilesConnections()) { em.remove(oldAssignment); } oldReport.getAttachedFilesConnections().clear(); for (SYSNR2PROCESS oldAssignment : oldReport.getAttachedQProcessConnections()) { em.remove(oldAssignment); } oldReport.getAttachedQProcessConnections().clear(); oldReport.setEditedBy(em.merge(OPDE.getLogin().getUser())); oldReport.setEditDate(new Date()); oldReport.setReplacedBy(newReport); em.getTransaction().commit(); final String keyNewDay = DateFormat.getDateInstance() .format(newReport.getPit()); final String keyOldDay = DateFormat.getDateInstance() .format(oldReport.getPit()); synchronized (contentmap) { contentmap.remove(keyNewDay); contentmap.remove(keyOldDay); } synchronized (linemap) { linemap.remove(oldReport); } synchronized (valuecache) { valuecache.get(keyOldDay).remove(nreport); valuecache.get(keyOldDay).add(oldReport); Collections.sort(valuecache.get(keyOldDay)); if (valuecache.containsKey(keyNewDay)) { valuecache.get(keyNewDay).add(newReport); Collections.sort(valuecache.get(keyNewDay)); } } synchronized (listUsedCommontags) { boolean reloadSearch = false; for (Commontags ctag : newReport.getCommontags()) { if (!listUsedCommontags.contains(ctag)) { listUsedCommontags.add(ctag); reloadSearch = true; } } if (reloadSearch) { prepareSearchArea(); } } if (minmax.isAfter(new DateTime(newReport.getPit()))) { minmax.setStart(new DateTime(newReport.getPit())); } if (minmax.isBefore(new DateTime(newReport.getPit()))) { minmax.setEnd(new DateTime(newReport.getPit())); } createCP4Day(new LocalDate(oldReport.getPit())); createCP4Day(new LocalDate(newReport.getPit())); buildPanel(); GUITools.scroll2show(jspReports, cpMap.get(keyNewDay), cpsReports, new Closure() { @Override public void execute(Object o) { GUITools.flashBackground(linemap.get(newReport), Color.YELLOW, 2); } }); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } else { reloadDisplay(true); } } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }); } }); btnEdit.setEnabled(NReportTools.isChangeable(nreport)); pnlMenu.add(btnEdit); /*** * ____ _ _ * | _ \ ___| | ___| |_ ___ * | | | |/ _ \ |/ _ \ __/ _ \ * | |_| | __/ | __/ || __/ * |____/ \___|_|\___|\__\___| * */ final JButton btnDelete = GUITools.createHyperlinkButton("nursingrecords.reports.btnDelete.tooltip", SYSConst.icon22delete, null); btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgYesNo( SYSTools.xx("misc.questions.delete1") + "<br/><i>" + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT).format( nreport.getPit()) + "</i><br/>" + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() { @Override public void execute(Object answer) { if (answer.equals(JOptionPane.YES_OPTION)) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); final NReport delReport = em.merge(nreport); em.lock(delReport, LockModeType.OPTIMISTIC); delReport.setDeletedBy(em.merge(OPDE.getLogin().getUser())); for (SYSNR2FILE oldAssignment : delReport .getAttachedFilesConnections()) { em.remove(oldAssignment); } delReport.getAttachedFilesConnections().clear(); for (SYSNR2PROCESS oldAssignment : delReport .getAttachedQProcessConnections()) { em.remove(oldAssignment); } delReport.getAttachedQProcessConnections().clear(); em.getTransaction().commit(); final String keyDay = DateFormat.getDateInstance() .format(delReport.getPit()); synchronized (contentmap) { contentmap.remove(keyDay); } synchronized (linemap) { linemap.remove(delReport); } synchronized (valuecache) { valuecache.get(keyDay).remove(nreport); valuecache.get(keyDay).add(delReport); Collections.sort(valuecache.get(keyDay)); } createCP4Day(new LocalDate(delReport.getPit())); buildPanel(); if (tbShowReplaced.isSelected()) { GUITools.flashBackground(linemap.get(delReport), Color.YELLOW, 2); } } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } else { reloadDisplay(true); } } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }); } }); btnDelete.setEnabled(NReportTools.isChangeable(nreport)); pnlMenu.add(btnDelete); /*** * _ _ _____ _ ____ * | |__ | |_ _ _|_ _|/ \ / ___|___ * | '_ \| __| '_ \| | / _ \| | _/ __| * | |_) | |_| | | | |/ ___ \ |_| \__ \ * |_.__/ \__|_| |_|_/_/ \_\____|___/ * */ final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple, null); btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT); btnTAGs.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { final JidePopup popup = new JidePopup(); final JPanel pnl = new JPanel(new BorderLayout(5, 5)); final PnlCommonTags pnlCommonTags = new PnlCommonTags(nreport.getCommontags(), true, 3); pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER); JButton btnApply = new JButton(SYSConst.icon22apply); pnl.add(btnApply, BorderLayout.SOUTH); btnApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); final NReport myReport = em.merge(nreport); em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT); myReport.getCommontags().clear(); for (Commontags commontag : pnlCommonTags.getListSelectedTags()) { myReport.getCommontags().add(em.merge(commontag)); } em.getTransaction().commit(); final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit()); synchronized (contentmap) { contentmap.remove(keyNewDay); } synchronized (linemap) { linemap.remove(nreport); } synchronized (valuecache) { valuecache.get(keyNewDay).remove(nreport); valuecache.get(keyNewDay).add(myReport); Collections.sort(valuecache.get(keyNewDay)); } synchronized (listUsedCommontags) { boolean reloadSearch = false; for (Commontags ctag : myReport.getCommontags()) { if (!listUsedCommontags.contains(ctag)) { listUsedCommontags.add(ctag); reloadSearch = true; } } if (reloadSearch) { prepareSearchArea(); } } createCP4Day(new LocalDate(myReport.getPit())); buildPanel(); GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2); } catch (OptimisticLockException ole) { OPDE.warn(ole); OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } else { reloadDisplay(true); } } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); popup.setMovable(false); popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS)); popup.setOwner(btnTAGs); popup.removeExcludedComponent(btnTAGs); pnl.setPreferredSize(new Dimension(350, 150)); popup.getContentPane().add(pnl); popup.setDefaultFocusComponent(pnl); GUITools.showPopup(popup, SwingConstants.WEST); } }); btnTAGs.setEnabled(NReportTools.isChangeable(nreport) && NReportTools.isMine(nreport)); pnlMenu.add(btnTAGs); /*** * _ _ __ __ _ _ * | |__ | |_ _ __ | \/ (_)_ __ _ _| |_ ___ ___ * | '_ \| __| '_ \| |\/| | | '_ \| | | | __/ _ \/ __| * | |_) | |_| | | | | | | | | | | |_| | || __/\__ \ * |_.__/ \__|_| |_|_| |_|_|_| |_|\__,_|\__\___||___/ * */ final JButton btnMinutes = GUITools.createHyperlinkButton("nursingrecords.reports.btnminutes.tooltip", SYSConst.icon22clock, null); btnMinutes.setAlignmentX(Component.RIGHT_ALIGNMENT); btnMinutes.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { final JPopupMenu menu = SYSCalendar.getMinutesMenu( new int[] { 1, 2, 3, 4, 5, 10, 15, 20, 30, 45, 60, 120, 240, 360 }, new Closure() { @Override public void execute(Object o) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); NReport myReport = em.merge(nreport); em.lock(myReport, LockModeType.OPTIMISTIC); myReport.setMinutes((Integer) o); myReport.setEditDate(new Date()); em.getTransaction().commit(); final String keyNewDay = DateFormat.getDateInstance() .format(myReport.getPit()); synchronized (contentmap) { contentmap.remove(keyNewDay); } synchronized (linemap) { linemap.remove(nreport); } synchronized (valuecache) { valuecache.get(keyNewDay).remove(nreport); valuecache.get(keyNewDay).add(myReport); Collections.sort(valuecache.get(keyNewDay)); } createCP4Day(new LocalDate(myReport.getPit())); buildPanel(); GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } else { reloadDisplay(true); } } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); menu.show(btnMinutes, 0, btnMinutes.getHeight()); } }); btnMinutes.setEnabled(!nreport.isObsolete() && NReportTools.isMine(nreport)); pnlMenu.add(btnMinutes); pnlMenu.add(new JSeparator()); /*** * _ _ _____ _ _ * | |__ | |_ _ __ | ___(_) | ___ ___ * | '_ \| __| '_ \| |_ | | |/ _ \/ __| * | |_) | |_| | | | _| | | | __/\__ \ * |_.__/ \__|_| |_|_| |_|_|\___||___/ * */ final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach, null); btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT); btnFiles.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { Closure fileHandleClosure = nreport.isObsolete() ? null : new Closure() { @Override public void execute(Object o) { EntityManager em = OPDE.createEM(); final NReport myReport = em.find(NReport.class, nreport.getID()); em.close(); final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit()); synchronized (contentmap) { contentmap.remove(keyNewDay); } synchronized (linemap) { linemap.remove(nreport); } synchronized (valuecache) { valuecache.get(keyNewDay).remove(nreport); valuecache.get(keyNewDay).add(myReport); Collections.sort(valuecache.get(keyNewDay)); } createCP4Day(new LocalDate(myReport.getPit())); buildPanel(); GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2); } }; new DlgFiles(nreport, fileHandleClosure); } }); btnFiles.setEnabled(OPDE.isFTPworking()); pnlMenu.add(btnFiles); /*** * _ _ ____ * | |__ | |_ _ __ | _ \ _ __ ___ ___ ___ ___ ___ * | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __| * | |_) | |_| | | | __/| | | (_) | (_| __/\__ \__ \ * |_.__/ \__|_| |_|_| |_| \___/ \___\___||___/___/ * */ final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip", SYSConst.icon22link, null); btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT); btnProcess.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgProcessAssign(nreport, new Closure() { @Override public void execute(Object o) { if (o == null) { return; } Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o; ArrayList<QProcess> assigned = result.getFirst(); ArrayList<QProcess> unassigned = result.getSecond(); EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); NReport myReport = em.merge(nreport); em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT); ArrayList<SYSNR2PROCESS> attached = new ArrayList<SYSNR2PROCESS>( myReport.getAttachedQProcessConnections()); for (SYSNR2PROCESS linkObject : attached) { if (unassigned.contains(linkObject.getQProcess())) { linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject); linkObject.getNReport().getAttachedQProcessConnections().remove(linkObject); em.merge(new PReport( SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": " + nreport.getTitle() + " ID: " + nreport.getID(), PReportTools.PREPORT_TYPE_REMOVE_ELEMENT, linkObject.getQProcess())); em.remove(linkObject); } } attached.clear(); for (QProcess qProcess : assigned) { java.util.List<QProcessElement> listElements = qProcess.getElements(); if (!listElements.contains(myReport)) { QProcess myQProcess = em.merge(qProcess); SYSNR2PROCESS myLinkObject = em .merge(new SYSNR2PROCESS(myQProcess, myReport)); em.merge(new PReport( SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": " + nreport.getTitle() + " ID: " + nreport.getID(), PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess)); qProcess.getAttachedNReportConnections().add(myLinkObject); myReport.getAttachedQProcessConnections().add(myLinkObject); } } em.getTransaction().commit(); final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit()); synchronized (contentmap) { contentmap.remove(keyNewDay); } synchronized (linemap) { linemap.remove(nreport); } synchronized (valuecache) { valuecache.get(keyNewDay).remove(nreport); valuecache.get(keyNewDay).add(myReport); Collections.sort(valuecache.get(keyNewDay)); } createCP4Day(new LocalDate(myReport.getPit())); buildPanel(); GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } else { reloadDisplay(true); } } catch (RollbackException ole) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); } }); pnlMenu.add(btnProcess); } return pnlMenu; }
From source file:org.opencms.ade.galleries.CmsGalleryService.java
/** * Builds a single search result list item for the client from a server-side search result.<p> * * @param cms the current CMS context/*from w ww. j a v a 2 s. co m*/ * @param sResult the server-side search result * @param presetResult the preselected result * * @return the client side search result item * * @throws CmsException if something goes wrong * @throws ParseException if date parsing fails */ private CmsResultItemBean buildSingleSearchResultItem(CmsObject cms, CmsGallerySearchResult sResult, CmsGallerySearchResult presetResult) throws CmsException, ParseException { Locale wpLocale = getWorkplaceLocale(); CmsResultItemBean bean = new CmsResultItemBean(); if (sResult == presetResult) { bean.setPreset(true); } bean.setReleasedAndNotExpired(sResult.isReleaseAndNotExpired(cms)); String path = sResult.getPath(); path = cms.getRequestContext().removeSiteRoot(path); // resource path as id bean.setPath(path); // title String rawTitle = CmsStringUtil.isEmptyOrWhitespaceOnly(sResult.getTitle()) ? CmsResource.getName(sResult.getPath()) : sResult.getTitle(); bean.setTitle(rawTitle); bean.setRawTitle(rawTitle); // resource type bean.setType(sResult.getResourceType()); CmsResource resultResource = cms.readResource(new CmsUUID(sResult.getStructureId()), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED); bean.setDetailResourceType(CmsResourceIcon.getDefaultFileOrDetailType(cms, resultResource)); // structured id bean.setClientId(sResult.getStructureId()); CmsVfsService.addLockInfo(cms, resultResource, bean); String permalinkId = sResult.getStructureId().toString(); String permalink = CmsStringUtil.joinPaths(OpenCms.getSystemInfo().getOpenCmsContext(), CmsPermalinkResourceHandler.PERMALINK_HANDLER, permalinkId); bean.setViewLink(permalink); // set nice resource type name as subtitle I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(sResult.getResourceType()); String resourceTypeDisplayName = CmsWorkplaceMessages.getResourceTypeName(wpLocale, type.getTypeName()); String description = sResult.getDescription(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(description)) { bean.setDescription(description); bean.addAdditionalInfo( Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_DESCRIPTION_0), description); } else { bean.setDescription(resourceTypeDisplayName); } bean.setUserLastModified(sResult.getUserLastModified()); Date lastModDate = sResult.getDateLastModified(); String formattedDate = lastModDate != null ? CmsDateUtil.getDateTime(lastModDate, DateFormat.MEDIUM, wpLocale) : ""; bean.setDateLastModified(formattedDate); if (!type.getTypeName().equals(CmsResourceTypeImage.getStaticTypeName())) { bean.addAdditionalInfo( Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_RESOURCE_TYPE_0), resourceTypeDisplayName); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(sResult.getExcerpt())) { bean.addAdditionalInfo( Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_EXCERPT_0), sResult.getExcerpt(), CmsListInfoBean.CSS_CLASS_MULTI_LINE); } if (type instanceof CmsResourceTypeImage) { CmsProperty copyrightProp = cms.readPropertyObject(resultResource, CmsPropertyDefinition.PROPERTY_COPYRIGHT, false); if (!copyrightProp.isNullProperty()) { bean.addAdditionalInfo( Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_COPYRIGHT_0), copyrightProp.getValue()); } CmsProperty imageDimensionProp = cms.readPropertyObject(resultResource, CmsPropertyDefinition.PROPERTY_IMAGE_SIZE, false); if (!imageDimensionProp.isNullProperty()) { String dimensions = imageDimensionProp.getValue(); dimensions = dimensions.substring(2).replace(",h:", " x "); bean.setDimension(dimensions); bean.addAdditionalInfo( Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_DIMENSION_0), dimensions); } } if (type instanceof CmsResourceTypeXmlContent) { CmsProperty elementModelProperty = cms.readPropertyObject(resultResource, CmsPropertyDefinition.PROPERTY_ELEMENT_MODEL, true); if (!elementModelProperty.isNullProperty()) { if (Boolean.valueOf(elementModelProperty.getValue()).booleanValue()) { bean.setIsCopyModel(true); } } } if (CmsResourceTypeXmlContainerPage.isModelReuseGroup(cms, resultResource)) { bean.setPseudoType(CmsGwtConstants.TYPE_MODELGROUP_REUSE); } bean.setResourceState(resultResource.getState()); bean.addAdditionalInfo(Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_SIZE_0), (sResult.getLength() / 1000) + " kb"); if (lastModDate != null) { bean.addAdditionalInfo( Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_DATE_CHANGED_0), CmsDateUtil.getDate(lastModDate, DateFormat.SHORT, getWorkplaceLocale())); } if ((sResult.getDateExpired().getTime() != CmsResource.DATE_EXPIRED_DEFAULT) && !sResult.getDateExpired().equals(CmsSearchFieldMapping.getDefaultDateExpired())) { bean.addAdditionalInfo( Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_RESULT_LABEL_DATE_EXPIRED_0), CmsDateUtil.getDate(sResult.getDateExpired(), DateFormat.SHORT, getWorkplaceLocale())); } bean.setNoEditReson(new CmsResourceUtil(cms, resultResource) .getNoEditReason(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms))); bean.setMarkChangedState(true); return bean; }