List of usage examples for java.lang Integer equals
public boolean equals(Object obj)
From source file:com.aurel.track.fieldType.runtime.matchers.run.SystemSelectMatcherRT.java
/** * Whether the value matches or not/*from w w w . j a v a2s .co m*/ * @param attributeValue * @return */ @Override public boolean match(Object attributeValue) { Boolean nullMatch = nullMatcher(attributeValue); if (nullMatch != null) { return nullMatch.booleanValue(); } if (attributeValue == null || matchValue == null) { return false; } Integer attributeValueSystemOption = null; Integer matcherValueSystemOption = null; try { attributeValueSystemOption = (Integer) attributeValue; } catch (Exception e) { LOGGER.warn("Converting the attribute value " + attributeValue + " of type " + attributeValue.getClass().getName() + " to Integer failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return false; } try { Integer[] matchValueArr = (Integer[]) matchValue; if (matchValueArr.length > 0) { matcherValueSystemOption = matchValueArr[0]; } } catch (Exception e) { LOGGER.warn("Converting the matcher value " + matchValue + " of type " + matchValue.getClass().getName() + " to Integer failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return false; } switch (relation) { case MatchRelations.EQUAL: return attributeValueSystemOption.equals(matcherValueSystemOption); case MatchRelations.NOT_EQUAL: return !attributeValueSystemOption.equals(matcherValueSystemOption); default: return false; } }
From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java
/** * Process request//from ww w . j a v a2 s .c om * <P> * * (Certificate Request - all "agent" profile cert requests made through a connector) * <P> * * (Certificate Request Processed - all automated "agent" profile based cert acceptance made through a connector) * <P> * * <ul> * <li>signed.audit LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST used when a profile cert request is made (before * approval process) * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a certificate request has just been * through the approval process * <li>signed.audit LOGGING_SIGNED_AUDIT_INTER_BOUNDARY_SUCCESS used when inter-CIMC_Boundary data transfer is * successful (this is used when data does not need to be captured) * </ul> * * @param source string containing source * @param sourceUserId string containing source user ID * @param msg PKI message * @param token the authentication token * @exception EBaseException an error has occurred * @return PKI message */ protected IPKIMessage processRequest(String source, String sourceUserId, IPKIMessage msg, IAuthToken token) throws EBaseException { String auditMessage = null; String auditSubjectID = sourceUserId; String auditProtectionMethod = SIGNED_AUDIT_PROTECTION_METHOD_SSL; String auditRequestType = msg.getReqType(); String auditRequesterID = msg.getReqId(); // additional parms for LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST String auditCertificateSubjectName = ILogger.SIGNED_AUDIT_EMPTY_VALUE; String subject = null; // "normalize" the "auditSubjectID" if (auditSubjectID != null) { auditSubjectID = auditSubjectID.trim(); } else { auditSubjectID = ILogger.UNIDENTIFIED; } // "normalize" the "auditRequestType" if (auditRequestType != null) { auditRequestType = auditRequestType.trim(); } else { auditRequestType = ILogger.SIGNED_AUDIT_EMPTY_VALUE; } // "normalize" the "auditRequesterID" if (auditRequesterID != null) { auditRequesterID = auditRequesterID.trim(); } else { auditRequesterID = ILogger.UNIDENTIFIED; } IPKIMessage replymsg = null; try { IRequestQueue queue = mAuthority.getRequestQueue(); String srcid = source + ":" + msg.getReqId(); // find request in request queue and return result. RequestId thisreqid = queue.findRequestBySourceId(srcid); IRequest thisreq = null; if (thisreqid != null) { thisreq = queue.findRequest(thisreqid); if (thisreq == null) { // strange case. String errormsg = "Cannot find request in request queue " + thisreqid; mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQUEST_ID_NOT_FOUND_1", thisreqid.toString())); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); // NOTE: The signed audit event // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST // does not yet matter at this point! throw new EBaseException(errormsg); } else { mAuthority.log(ILogger.LL_INFO, "Found request " + thisreqid + " for " + srcid); replymsg = CMS.getHttpPKIMessage(); replymsg.fromRequest(thisreq); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.SUCCESS, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); // NOTE: The signed audit event // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST // does not yet matter at this point! return replymsg; } } // if not found process request. thisreq = queue.newRequest(msg.getReqType()); CMS.debug("ConnectorServlet: created requestId=" + thisreq.getRequestId().toString()); thisreq.setSourceId(srcid); // NOTE: For the following signed audit message, since we only // care about the "msg.toRequest( thisreq );" command, and // since this command does not throw an EBaseException // (which is the only exception designated by this method), // then this code does NOT need to be contained within its // own special try/catch block. msg.toRequest(thisreq); if (isProfileRequest(thisreq)) { X509CertInfo info = thisreq.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO); try { CertificateSubjectName sn = (CertificateSubjectName) info.get(X509CertInfo.SUBJECT); // if the cert subject name is NOT MISSING, retrieve the // actual "auditCertificateSubjectName" and "normalize" // it if (sn != null) { subject = sn.toString(); if (subject != null) { // NOTE: This is ok even if the cert subject // name is "" (empty)! auditCertificateSubjectName = subject.trim(); } } // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.PROFILE_CERT_REQUEST, auditSubjectID, ILogger.SUCCESS, auditRequesterID, auditProfileID(), auditCertificateSubjectName); audit(auditMessage); } catch (CertificateException e) { CMS.debug("ConnectorServlet: processRequest " + e.toString()); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.PROFILE_CERT_REQUEST, auditSubjectID, ILogger.FAILURE, auditRequesterID, auditProfileID(), auditCertificateSubjectName); audit(auditMessage); } catch (IOException e) { CMS.debug("ConnectorServlet: processRequest " + e.toString()); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.PROFILE_CERT_REQUEST, auditSubjectID, ILogger.FAILURE, auditRequesterID, auditProfileID(), auditCertificateSubjectName); audit(auditMessage); } } thisreq.setExtData(IRequest.AUTH_TOKEN, token); if (StringUtils.isNotEmpty(msg.getReqRealm())) { thisreq.setRealm(msg.getReqRealm()); } // setting requestor type must come after copy contents. because // requestor is a regular attribute. thisreq.setExtData(IRequest.REQUESTOR_TYPE, IRequest.REQUESTOR_RA); mAuthority.log(ILogger.LL_INFO, "Processing remote request " + srcid); // Set this so that request's updateBy is recorded SessionContext s = SessionContext.getContext(); if (s.get(SessionContext.USER_ID) == null) { s.put(SessionContext.USER_ID, sourceUserId); } if (s.get(SessionContext.REQUESTER_ID) == null) { s.put(SessionContext.REQUESTER_ID, msg.getReqId()); } //CMS.debug("ConnectorServlet: calling processRequest instance=" + // thisreq); if (isProfileRequest(thisreq)) { normalizeProfileRequest(thisreq); } CMS.debug("ConnectorServlet: calling processRequest"); try { queue.processRequest(thisreq); } finally { if (isProfileRequest(thisreq)) { X509CertImpl x509cert = thisreq.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT); if (x509cert != null) { audit(CertRequestProcessedEvent.createSuccessEvent(auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_ACCEPTANCE, x509cert)); } else { audit(CertRequestProcessedEvent.createFailureEvent(auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_REJECTION, ILogger.SIGNED_AUDIT_EMPTY_VALUE)); } } } replymsg = CMS.getHttpPKIMessage(); replymsg.fromRequest(thisreq); CMS.debug("ConnectorServlet: replymsg.reqStatus=" + replymsg.getReqStatus()); //for audit log String agentID = sourceUserId; String initiative = AuditFormat.FROMRA + " trustedManagerID: " + agentID + " remote reqID " + msg.getReqId(); String authMgr = AuditFormat.NOAUTH; if (token != null) { authMgr = token.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME); } if (isProfileRequest(thisreq)) { // XXX audit log CMS.debug("ConnectorServlet: done requestId=" + thisreq.getRequestId().toString()); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.SUCCESS, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); // NOTE: The signed audit event // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST // has already been logged at this point! return replymsg; } // Get the certificate info from the request X509CertInfo x509Info[] = thisreq.getExtDataInCertInfoArray(IRequest.CERT_INFO); try { if (!thisreq.getRequestStatus().equals(RequestStatus.COMPLETE)) { if (x509Info != null) { for (int i = 0; i < x509Info.length; i++) { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.FORMAT, new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative, authMgr, thisreq.getRequestStatus(), x509Info[i].get(X509CertInfo.SUBJECT), "" }); } } else { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.NODNFORMAT, new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative, authMgr, thisreq.getRequestStatus() }); } } else { if (thisreq.getRequestType().equals(IRequest.ENROLLMENT_REQUEST)) { // XXX make the repeat record. // Get the certificate(s) from the request X509CertImpl x509Certs[] = null; if (x509Info != null) x509Certs = thisreq.getExtDataInCertArray(IRequest.ISSUED_CERTS); // return potentially more than one certificates. if (x509Certs != null) { for (int i = 0; i < x509Certs.length; i++) { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.FORMAT, new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative, authMgr, "completed", x509Certs[i].getSubjectDN(), "cert issued serial number: 0x" + x509Certs[i].getSerialNumber().toString(16) }); } } else { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.NODNFORMAT, new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative, authMgr, "completed" }); } } else if (thisreq.getRequestType().equals(IRequest.RENEWAL_REQUEST)) { X509CertImpl[] certs = thisreq.getExtDataInCertArray(IRequest.OLD_CERTS); X509CertImpl old_cert = certs[0]; certs = thisreq.getExtDataInCertArray(IRequest.ISSUED_CERTS); X509CertImpl renewed_cert = certs[0]; if (old_cert != null && renewed_cert != null) { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.RENEWALFORMAT, new Object[] { thisreq.getRequestId(), initiative, authMgr, "completed", old_cert.getSubjectDN(), old_cert.getSerialNumber().toString(16), "new serial number: 0x" + renewed_cert.getSerialNumber().toString(16) }); } else { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.NODNFORMAT, new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative, authMgr, "completed with error" }); } } else if (thisreq.getRequestType().equals(IRequest.REVOCATION_REQUEST)) { Certificate[] oldCerts = thisreq.getExtDataInCertArray(IRequest.OLD_CERTS); RevokedCertImpl crlentries[] = thisreq.getExtDataInRevokedCertArray(IRequest.REVOKED_CERTS); CRLExtensions crlExts = crlentries[0].getExtensions(); int reason = 0; if (crlExts != null) { Enumeration<Extension> enum1 = crlExts.getElements(); while (enum1.hasMoreElements()) { Extension ext = enum1.nextElement(); if (ext instanceof CRLReasonExtension) { reason = ((CRLReasonExtension) ext).getReason().toInt(); break; } } } int count = oldCerts.length; Integer result = thisreq.getExtDataInInteger(IRequest.RESULT); if (result.equals(IRequest.RES_ERROR)) { String[] svcErrors = thisreq.getExtDataInStringArray(IRequest.SVCERRORS); if (svcErrors != null && svcErrors.length > 0) { for (int i = 0; i < svcErrors.length; i++) { String err = svcErrors[i]; if (err != null) { for (int j = 0; j < count; j++) { if (oldCerts[j] != null) { if (oldCerts[j] instanceof X509CertImpl) { X509CertImpl cert = (X509CertImpl) oldCerts[j]; mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.DOREVOKEFORMAT, new Object[] { thisreq.getRequestId(), initiative, "completed with error: " + err, cert.getSubjectDN(), cert.getSerialNumber().toString(16), RevocationReason.fromInt(reason).toString() }); } } } } } } } else { // the success. for (int j = 0; j < count; j++) { if (oldCerts[j] != null) { if (oldCerts[j] instanceof X509CertImpl) { X509CertImpl cert = (X509CertImpl) oldCerts[j]; mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.DOREVOKEFORMAT, new Object[] { thisreq.getRequestId(), initiative, "completed", cert.getSubjectDN(), cert.getSerialNumber().toString(16), RevocationReason.fromInt(reason).toString() }); } } } } } else { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.NODNFORMAT, new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative, authMgr, "completed" }); } } // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.SUCCESS, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); } catch (IOException e) { CMS.debug("ConnectorServlet: process " + e.toString()); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); } catch (CertificateException e) { CMS.debug("ConnectorServlet: process " + e.toString()); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); } catch (Exception e) { CMS.debug("ConnectorServlet: process " + e.toString()); // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); } finally { SessionContext.releaseContext(); } // NOTE: The signed audit event // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST // has already been logged at this point! return replymsg; } catch (EBaseException e) { // store a message in the signed audit log file auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE, auditProtectionMethod, auditRequestType, auditRequesterID); audit(auditMessage); // NOTE: The signed audit event // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST // has either already been logged, or // does not yet matter at this point! return replymsg; } }
From source file:com.sshtools.common.ui.SshToolsApplicationPanel.java
/** * Rebuild all the action components such as toobar, context menu *//*from www. j a va 2 s. c om*/ public void rebuildActionComponents() { // Clear the current state of the component log.debug("Rebuild action components"); toolBar.removeAll(); // Vector enabledActions = new Vector(); for (Iterator i = actions.iterator(); i.hasNext();) { StandardAction a = (StandardAction) i.next(); String n = (String) a.getValue(Action.NAME); Boolean s = (Boolean) actionsVisible.get(n); if (s == null) { s = Boolean.TRUE; } if (Boolean.TRUE.equals(s)) { log.debug("Action " + n + " is enabled."); enabledActions.add(a); } else { log.debug("Action " + n + " not enabled."); } } // Build the tool bar, grouping the actions Vector v = new Vector(); for (Iterator i = enabledActions.iterator(); i.hasNext();) { StandardAction a = (StandardAction) i.next(); if (Boolean.TRUE.equals((Boolean) a.getValue(StandardAction.ON_TOOLBAR))) { v.addElement(a); } } Collections.sort(v, new ToolBarActionComparator()); Integer grp = null; for (Iterator i = v.iterator(); i.hasNext();) { StandardAction z = (StandardAction) i.next(); if ((grp != null) && !grp.equals((Integer) z.getValue(StandardAction.TOOLBAR_GROUP))) { toolBar.add(new ToolBarSeparator()); } if (Boolean.TRUE.equals((Boolean) z.getValue(StandardAction.IS_TOGGLE_BUTTON))) { ToolToggleButton tBtn = new ToolToggleButton(z); toolBar.add(tBtn); } else { ToolButton btn = new ToolButton(z); toolBar.add(btn); } grp = (Integer) z.getValue(StandardAction.TOOLBAR_GROUP); } toolBar.revalidate(); toolBar.repaint(); // Build the context menu, grouping the actions Vector c = new Vector(); contextMenu.removeAll(); for (Iterator i = enabledActions.iterator(); i.hasNext();) { StandardAction a = (StandardAction) i.next(); if (Boolean.TRUE.equals((Boolean) a.getValue(StandardAction.ON_CONTEXT_MENU))) { c.addElement(a); } } Collections.sort(c, new ContextActionComparator()); grp = null; for (Iterator i = c.iterator(); i.hasNext();) { StandardAction z = (StandardAction) i.next(); if ((grp != null) && !grp.equals((Integer) z.getValue(StandardAction.CONTEXT_MENU_GROUP))) { contextMenu.addSeparator(); } contextMenu.add(z); grp = (Integer) z.getValue(StandardAction.CONTEXT_MENU_GROUP); } contextMenu.revalidate(); // Build the menu bar menuBar.removeAll(); v.removeAllElements(); for (Enumeration e = enabledActions.elements(); e.hasMoreElements();) { StandardAction a = (StandardAction) e.nextElement(); if (Boolean.TRUE.equals((Boolean) a.getValue(StandardAction.ON_MENUBAR))) { v.addElement(a); } } Vector menus = (Vector) actionMenus.clone(); Collections.sort(menus); HashMap map = new HashMap(); for (Iterator i = v.iterator(); i.hasNext();) { StandardAction z = (StandardAction) i.next(); String menuName = (String) z.getValue(StandardAction.MENU_NAME); if (menuName == null) { log.error("Action " + z.getName() + " doesnt specify a value for " + StandardAction.MENU_NAME); } else { String m = (String) z.getValue(StandardAction.MENU_NAME); ActionMenu menu = getActionMenu(menus.iterator(), m); if (menu == null) { log.error("Action menu " + z.getName() + " does not exist"); } else { Vector x = (Vector) map.get(menu.name); if (x == null) { x = new Vector(); map.put(menu.name, x); } x.addElement(z); } } } for (Iterator i = menus.iterator(); i.hasNext();) { ActionMenu m = (ActionMenu) i.next(); Vector x = (Vector) map.get(m.name); if (x != null) { Collections.sort(x, new MenuItemActionComparator()); JMenu menu = new JMenu(m.displayName); menu.setMnemonic(m.mnemonic); grp = null; for (Iterator j = x.iterator(); j.hasNext();) { StandardAction a = (StandardAction) j.next(); Integer g = (Integer) a.getValue(StandardAction.MENU_ITEM_GROUP); if ((grp != null) && !g.equals(grp)) { menu.addSeparator(); } grp = g; if (a instanceof MenuAction) { JMenu mnu = (JMenu) a.getValue(MenuAction.MENU); menu.add(mnu); } else { JMenuItem item = new JMenuItem(a); menu.add(item); } } menuBar.add(menu); } else { log.error("Can't find menu " + m.name); } } menuBar.validate(); menuBar.repaint(); }
From source file:com.netscape.cms.servlet.cert.DoRevoke.java
/** * Process cert status change request/*from w w w . j a v a2s . c o m*/ * <P> * * (Certificate Request - either an "agent" cert status change request, or an "EE" cert status change request) * <P> * * (Certificate Request Processed - either an "agent" cert status change request, or an "EE" cert status change * request) * <P> * * <ul> * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when a cert status change request (e. g. - * "revocation") is made (before approval process) * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a certificate status is * changed (revoked, expired, on-hold, off-hold) * </ul> * * @param argSet CMS template parameters * @param header argument block * @param reason revocation reason (0 - Unspecified, 1 - Key compromised, * 2 - CA key compromised; should not be used, 3 - Affiliation changed, * 4 - Certificate superceded, 5 - Cessation of operation, or * 6 - Certificate is on hold) * @param invalidityDate certificate validity date * @param initiative string containing the audit format * @param req HTTP servlet request * @param resp HTTP servlet response * @param verifiedRecordCount number of verified records * @param revokeAll string containing information on all of the * certificates to be revoked * @param totalRecordCount total number of records (verified and unverified) * @param eeSerialNumber BigInteger containing the end-entity certificate * serial number * @param eeSubjectDN string containing the end-entity certificate subject * distinguished name (DN) * @param comments string containing certificate comments * @param locale the system locale * @exception EBaseException an error has occurred */ private void process(CMSTemplateParams argSet, IArgBlock header, int reason, Date invalidityDate, String initiative, HttpServletRequest req, HttpServletResponse resp, int verifiedRecordCount, String revokeAll, int totalRecordCount, BigInteger eeSerialNumber, String eeSubjectDN, String comments, Locale locale) throws EBaseException { CMS.debug("DoRevoke: eeSerialNumber: " + eeSerialNumber); long startTime = CMS.getCurrentDate().getTime(); RevocationProcessor processor = new RevocationProcessor(servletConfig.getServletName(), getLocale(req)); processor.setStartTime(startTime); processor.setInitiative(initiative); processor.setSerialNumber(eeSerialNumber == null ? null : new CertId(eeSerialNumber)); RevocationReason revReason = RevocationReason.fromInt(reason); processor.setRevocationReason(revReason); processor.setRequestType( processor.getRevocationReason() == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD : RevocationProcessor.REVOKE); processor.setInvalidityDate(invalidityDate); processor.setComments(comments); Hashtable<BigInteger, Long> nonceMap = new Hashtable<BigInteger, Long>(); X509Certificate clientCert = getSSLClientCertificate(req); if (mAuthority instanceof ICertificateAuthority) { processor.setAuthority(certAuthority); if (certAuthority.noncesEnabled()) { String nonces = req.getParameter("nonce"); if (nonces == null) { throw new ForbiddenException("Missing nonce."); } // parse serial numbers and nonces for (String s : nonces.split(",")) { String[] elements = s.split(":"); BigInteger serialNumber = new BigInteger(elements[0].trim()); Long nonce = new Long(elements[1].trim()); nonceMap.put(serialNumber, nonce); } } } try { processor.createCRLExtension(); if (mAuthority instanceof ICertificateAuthority) { Enumeration<ICertRecord> e = mCertDB.searchCertificates(revokeAll, totalRecordCount, mTimeLimits); while (e != null && e.hasMoreElements()) { ICertRecord targetRecord = e.nextElement(); X509CertImpl targetCert = targetRecord.getCertificate(); // Verify end-entity cert is not revoked. // TODO: This should be checked during authentication. if (eeSerialNumber != null && eeSerialNumber.equals(targetCert.getSerialNumber()) && targetRecord.getStatus().equals(ICertRecord.STATUS_REVOKED)) { processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERTIFICATE_ALREADY_REVOKED_1", targetRecord.getSerialNumber().toString(16))); throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED")); } IArgBlock rarg = CMS.createArgBlock(); rarg.addStringValue("serialNumber", targetCert.getSerialNumber().toString(16)); try { if (mAuthority instanceof ICertificateAuthority && certAuthority.noncesEnabled() && !processor.isMemberOfSubsystemGroup(clientCert)) { // validate nonce for each certificate Long nonce = nonceMap.get(targetRecord.getSerialNumber()); processor.validateNonce(req, "cert-revoke", targetRecord.getSerialNumber(), nonce); } processor.validateCertificateToRevoke(eeSubjectDN, targetRecord, false); processor.addCertificateToRevoke(targetCert); rarg.addStringValue("error", null); } catch (PKIException ex) { rarg.addStringValue("error", ex.getMessage()); } argSet.addRepeatRecord(rarg); } } else if (mAuthority instanceof IRegistrationAuthority) { String reqIdStr = req.getParameter("requestId"); Collection<CertId> certSerialNumbers = new ArrayList<CertId>(); if (revokeAll != null && revokeAll.length() > 0) { for (int i = revokeAll.indexOf('='); i > -1; i = revokeAll.indexOf('=', i)) { i++; // skip spaces while (i < revokeAll.length() && revokeAll.charAt(i) == ' ') { i++; } // xxxx decimal serial number? String legalDigits = "0123456789"; int j = i; // find legal digits while (j < revokeAll.length() && legalDigits.indexOf(revokeAll.charAt(j)) != -1) { j++; } if (j > i) { certSerialNumbers.add(new CertId(revokeAll.substring(i, j))); } } } if (reqIdStr != null && reqIdStr.length() > 0 && certSerialNumbers.size() > 0) { IRequest certReq = mRequestQueue.findRequest(new RequestId(reqIdStr)); X509CertImpl[] certs = certReq.getExtDataInCertArray(IRequest.OLD_CERTS); boolean authorized = false; for (int i = 0; i < certs.length; i++) { boolean addToList = false; for (CertId certSerialNumber : certSerialNumbers) { //xxxxx serial number in decimal? if (certs[i].getSerialNumber().equals(certSerialNumber.toBigInteger()) && eeSubjectDN != null && eeSubjectDN.equals(certs[i].getSubjectDN().toString())) { addToList = true; break; } } if (eeSerialNumber != null && eeSerialNumber.equals(certs[i].getSerialNumber())) { authorized = true; } if (addToList) { IArgBlock rarg = CMS.createArgBlock(); rarg.addStringValue("serialNumber", certs[i].getSerialNumber().toString(16)); processor.addCertificateToRevoke(certs[i]); rarg.addStringValue("error", null); argSet.addRepeatRecord(rarg); } } if (!authorized) { processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQ_AUTH_REVOKED_CERT")); throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED")); } } else { String b64eCert = req.getParameter("b64eCertificate"); if (b64eCert != null) { // BASE64Decoder decoder = new BASE64Decoder(); // byte[] certBytes = decoder.decodeBuffer(b64eCert); byte[] certBytes = Utils.base64decode(b64eCert); X509CertImpl cert = new X509CertImpl(certBytes); IArgBlock rarg = CMS.createArgBlock(); rarg.addStringValue("serialNumber", cert.getSerialNumber().toString(16)); processor.addCertificateToRevoke(cert); rarg.addStringValue("error", null); argSet.addRepeatRecord(rarg); } } } int count = processor.getCertificates().size(); if (count == 0) { processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO")); throw new ECMSGWException(CMS.getLogMessage("CMSGW_REVOCATION_ERROR_CERT_NOT_FOUND")); } header.addIntegerValue("totalRecordCount", count); processor.createRevocationRequest(); processor.auditChangeRequest(ILogger.SUCCESS); } catch (ForbiddenException e) { throw new EAuthzException(CMS.getUserMessage(locale, "CMS_AUTHORIZATION_ERROR")); } catch (CertificateException e) { processor.log(ILogger.LL_FAILURE, "Error " + e); processor.auditChangeRequest(ILogger.FAILURE); // TODO: throw exception or return? // throw new EBaseException(e.getMessage()); return; } catch (EBaseException e) { processor.log(ILogger.LL_FAILURE, "Error " + e); processor.auditChangeRequest(ILogger.FAILURE); throw e; } catch (IOException e) { processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString())); processor.auditChangeRequest(ILogger.FAILURE); throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED")); } // change audit processing from "REQUEST" to "REQUEST_PROCESSED" // to distinguish which type of signed audit log message to save // as a failure outcome in case an exception occurs try { processor.processRevocationRequest(); IRequest revReq = processor.getRequest(); // retrieve the request status RequestStatus status = revReq.getRequestStatus(); processor.setRequestStatus(status); String type = revReq.getRequestType(); // The SVC_PENDING check has been added for the Cloned CA request // that is meant for the Master CA. From Clone's point of view // the request is complete if (status == RequestStatus.COMPLETE || status == RequestStatus.SVC_PENDING && type.equals(IRequest.CLA_CERT4CRL_REQUEST)) { header.addStringValue("revoked", "yes"); Integer updateCRLResult = revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS); if (updateCRLResult != null) { header.addStringValue("updateCRL", "yes"); if (updateCRLResult.equals(IRequest.RES_SUCCESS)) { header.addStringValue("updateCRLSuccess", "yes"); } else { header.addStringValue("updateCRLSuccess", "no"); String crlError = revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR); if (crlError != null) header.addStringValue("updateCRLError", crlError); } // let known crl publishing status too. Integer publishCRLResult = revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS); if (publishCRLResult != null) { if (publishCRLResult.equals(IRequest.RES_SUCCESS)) { header.addStringValue("publishCRLSuccess", "yes"); } else { header.addStringValue("publishCRLSuccess", "no"); String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR); if (publError != null) header.addStringValue("publishCRLError", publError); } } } if (mAuthority instanceof ICertificateAuthority) { // let known update and publish status of all crls. Enumeration<ICRLIssuingPoint> otherCRLs = ((ICertificateAuthority) mAuthority) .getCRLIssuingPoints(); while (otherCRLs.hasMoreElements()) { ICRLIssuingPoint crl = otherCRLs.nextElement(); String crlId = crl.getId(); if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL)) continue; String updateStatusStr = crl.getCrlUpdateStatusStr(); Integer updateResult = revReq.getExtDataInInteger(updateStatusStr); if (updateResult != null) { if (updateResult.equals(IRequest.RES_SUCCESS)) { CMS.debug("DoRevoke: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER", updateStatusStr)); header.addStringValue(updateStatusStr, "yes"); } else { String updateErrorStr = crl.getCrlUpdateErrorStr(); CMS.debug("DoRevoke: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO", updateStatusStr)); header.addStringValue(updateStatusStr, "no"); String error = revReq.getExtDataInString(updateErrorStr); if (error != null) header.addStringValue(updateErrorStr, error); } String publishStatusStr = crl.getCrlPublishStatusStr(); Integer publishResult = revReq.getExtDataInInteger(publishStatusStr); if (publishResult == null) continue; if (publishResult.equals(IRequest.RES_SUCCESS)) { header.addStringValue(publishStatusStr, "yes"); } else { String publishErrorStr = crl.getCrlPublishErrorStr(); header.addStringValue(publishStatusStr, "no"); String error = revReq.getExtDataInString(publishErrorStr); if (error != null) header.addStringValue(publishErrorStr, error); } } } } if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) { header.addStringValue("dirEnabled", "yes"); Integer[] ldapPublishStatus = revReq.getExtDataInIntegerArray("ldapPublishStatus"); int certsToUpdate = 0; int certsUpdated = 0; if (ldapPublishStatus != null) { certsToUpdate = ldapPublishStatus.length; for (int i = 0; i < certsToUpdate; i++) { if (ldapPublishStatus[i] == IRequest.RES_SUCCESS) { certsUpdated++; } } } header.addIntegerValue("certsUpdated", certsUpdated); header.addIntegerValue("certsToUpdate", certsToUpdate); // add crl publishing status. String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR); if (publError != null) { header.addStringValue("crlPublishError", publError); } } else { header.addStringValue("dirEnabled", "no"); } header.addStringValue("error", null); } else { if (status == RequestStatus.PENDING || status == RequestStatus.REJECTED) { header.addStringValue("revoked", status.toString()); } else { header.addStringValue("revoked", "no"); } Vector<String> errors = revReq.getExtDataInStringVector(IRequest.ERRORS); if (errors != null) { StringBuilder errInfo = new StringBuilder(); for (int i = 0; i < errors.size(); i++) { errInfo.append(errors.elementAt(i)); errInfo.append("\n"); } header.addStringValue("error", errInfo.toString()); } else if (status == RequestStatus.PENDING) { header.addStringValue("error", "Request Pending"); } else { header.addStringValue("error", null); } } processor.auditChangeRequestProcessed(ILogger.SUCCESS); } catch (EBaseException e) { processor.log(ILogger.LL_FAILURE, "Error " + e); processor.auditChangeRequestProcessed(ILogger.FAILURE); throw e; } }
From source file:iddb.api.ServerManager.java
public static Server getAuthorizedServer(String key, String remoteAddress, String serverName, String publicIp, Integer port) throws UnauthorizedUpdateException { Server server = serverDAO.findByUid(key); if (server == null) { // Compose. StringBuilder builder = new StringBuilder("Se intenta actualizar servidor no existente.\n"); builder.append("Key: " + key).append("\n"); if (serverName != null) builder.append("Nombre: " + serverName).append("\n"); if (remoteAddress != null) builder.append("IP: " + remoteAddress).append("\n"); String message = builder.toString(); // Throw. throw new UnauthorizedUpdateException(message); }/*from w ww .j a va2 s. c o m*/ if (server.getDisabled()) { // Compose. StringBuilder builder = new StringBuilder("Intento de actualizar servidor deshabilitado.\n"); builder.append("Key: " + key).append("\n"); if (serverName != null) builder.append("Nombre: " + serverName).append("\n"); if (remoteAddress != null) builder.append("IP: " + remoteAddress).append("\n"); String message = builder.toString(); // Throw. throw new UnauthorizedUpdateException(message); } if (StringUtils.isNotEmpty(remoteAddress) && StringUtils.isNotEmpty(server.getAddress()) && !remoteAddress.equals(server.getAddress())) { // Compose. StringBuilder builder = new StringBuilder("Intento de actualizar desde IP no autorizada.\n"); builder.append("Key: " + key).append("\n"); if (serverName != null) builder.append("Nombre: " + serverName).append("\n"); if (remoteAddress != null) builder.append("IP: " + remoteAddress).append("\n"); String message = builder.toString(); // Throw. throw new UnauthorizedUpdateException(message); } if (port != null && StringUtils.isNotEmpty(server.getDisplayAddress())) { try { String[] pIp = server.getDisplayAddress().split(":"); if (!(publicIp.equals(pIp[0]) && port.equals(Integer.parseInt(pIp[1])))) { // Compose. StringBuilder builder = new StringBuilder( "Intento de actualizar desde IP:PORT no autorizado.\n"); builder.append("Key: " + key).append("\n"); if (serverName != null) builder.append("Nombre: " + serverName).append("\n"); if (remoteAddress != null) builder.append("IP: " + remoteAddress).append("\n"); builder.append("IP Pblica: " + publicIp).append("\n"); builder.append("Puerto: " + port.toString()).append("\n"); String message = builder.toString(); // Throw. throw new UnauthorizedUpdateException(message); } } catch (Exception e) { log.error(e.getMessage()); } } return server; }
From source file:com.erudika.scoold.utils.LanguageUtils.java
/** * Updates the progress for all languages. * @param langCode the 2-letter language code * @param value {@link #PLUS}, {@link #MINUS} or the total percent of completion (0-100) *//*from w ww .jav a 2 s . co m*/ private void updateTranslationProgressMap(String langCode, int value) { if (getDefaultLanguageCode().equals(langCode)) { return; } double defsize = getDefaultLanguage().size(); double approved = value; Map<String, Integer> progress = getTranslationProgressMap(); Integer percent = progress.get(langCode); if (value == PLUS) { approved = Math.round(percent * (defsize / 100) + 1); } else if (value == MINUS) { approved = Math.round(percent * (defsize / 100) - 1); } // allow 3 identical words per language (i.e. Email, etc) if (approved >= defsize - 5) { approved = defsize; } if (((int) defsize) == 0) { progress.put(langCode, 0); } else { progress.put(langCode, (int) ((approved / defsize) * 100)); } Sysprop updatedProgress = new Sysprop(progressKey); for (Map.Entry<String, Integer> entry : progress.entrySet()) { updatedProgress.addProperty(entry.getKey(), entry.getValue()); } langProgressCache = updatedProgress; if (percent < 100 && !percent.equals(progress.get(langCode))) { pc.create(updatedProgress); } }
From source file:com.redhat.rhn.frontend.xmlrpc.user.UserHandler.java
/** * Toggles whether or not a user users pamAuthentication or the basic RHN db auth. * @param loggedInUser The current user/*from ww w. j ava2 s .c om*/ * @param login The login for the user you would like to change * @param val The value you would like to set this to (1 = true, 0 = false) * @return Returns 1 if successful (exception otherwise) * @throws FaultException A FaultException is thrown if the user doesn't have access * to lookup the user corresponding to login or if the user does not exist. * * @xmlrpc.doc Toggles whether or not a user uses PAM authentication or * basic RHN authentication. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param #param("int", "pam_value") * #options() * #item("1 to enable PAM authentication") * #item("0 to disable.") * #options_end() * @xmlrpc.returntype #return_int_success() */ public int usePamAuthentication(User loggedInUser, String login, Integer val) throws FaultException { // Only org admins can use this method. ensureOrgAdmin(loggedInUser); User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); if (val.equals(new Integer(1))) { target.setUsePamAuthentication(true); } else { target.setUsePamAuthentication(false); } UserManager.storeUser(target); return 1; }
From source file:nc.noumea.mairie.organigramme.viewmodel.EditEntiteDtoViewModel.java
private List<FichePosteTreeNodeDto> getListeFromFdpAndNiveau(List<FichePosteTreeNodeDto> listeEnfant, Integer niveau, List<FichePosteTreeNodeDto> result) { if (niveau.equals(0)) { result.addAll(listeEnfant);//from ww w . j a v a 2 s . c om return result; } for (FichePosteTreeNodeDto entiteDtoEnfant : listeEnfant) { getListeFromFdpAndNiveau(entiteDtoEnfant.getFichePostesEnfant(), niveau - 1, result); } return result; }
From source file:com.aurel.track.exchange.track.importer.TrackImportBL.java
/** * add/upgrade of the workItem and the history * /* w ww. j av a 2s . c om*/ * @param exchangeWorkItem * @param internalWorkItemBean * @param transactionUuidsForInternalWorkitem * @param dropDownMatcherMap */ private static int addUpgradeWorkItem(ExchangeWorkItem exchangeWorkItem, ReportBeanWithHistory reportBeanWithHistory, WorkItemContext workItemContext, Set<String> transactionUuidsForInternalWorkitem, Map<String, Map<Integer, Integer>> dropDownMatcherMap, List<String> externalWorkItemUuidsWithLink, List<String> externalTransactionUuidsWithLink, Map<Integer, String> externalWorkItemNrToInternalWkItemNr) throws ImportExceptionList { int result = NOSAVE; TWorkItemBean internalWorkItemBean = workItemContext.getWorkItemBean(); boolean isNew = true; if (internalWorkItemBean.getObjectID() != null) { isNew = false; } Map<Integer, Integer> fieldsMatcherMap = dropDownMatcherMap.get(ExchangeFieldNames.FIELD); /** * sets/updates the workItem actual values */ Map<String, Object> actualFieldValuesMap = exchangeWorkItem.getActualFieldValuesMap(); Integer externalWorkItemID = exchangeWorkItem.getWorkItemID(); String externalUUID = exchangeWorkItem.getUuid(); if (internalWorkItemBean.getUuid() == null) { // set the uuid of the internal workItem to the external workItem's // uuid (for new workItems) internalWorkItemBean.setUuid(externalUUID); } String strExteranalLastEditDate = (String) actualFieldValuesMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_LASTMODIFIEDDATE, null)); Date externalLastEdit = DateTimeUtils.getInstance().parseISODateTime(strExteranalLastEditDate); if (actualFieldValuesMap != null && externalIsMoreRecent(externalLastEdit, internalWorkItemBean.getLastEdit(), "workItem", externalWorkItemID)) { for (String externalKey : actualFieldValuesMap.keySet()) { Integer[] parts = MergeUtil.getParts(externalKey); Integer externalFieldID = parts[0]; Integer parameterCode = parts[1]; if (!SystemFields.INTEGER_ISSUENO.equals(externalFieldID) && !SystemFields.INTEGER_SUPERIORWORKITEM.equals(externalFieldID)) { // do not set the issueNo and parentNo values because they // will be different from the external values Integer internalFieldID; if (fieldsMatcherMap.get(externalFieldID) != null) { // replace the external fieldID with the internal // fieldID internalFieldID = fieldsMatcherMap.get(externalFieldID); } else { LOGGER.warn("No internal fieldID found for external fieldID " + externalFieldID + " and external workItem " + externalWorkItemID + ". The field cannot be saved"); continue; } // the issue number shouldn't be set! Object exchangeAttribut = actualFieldValuesMap.get(externalKey); // do not set the issue number (because it either exists or // will be generated) IFieldTypeRT internalFieldTypeRT = FieldTypeManager.getFieldTypeRT(internalFieldID, parameterCode); if (internalFieldTypeRT != null) { if (exchangeAttribut != null && (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION || internalFieldTypeRT.getValueType() == ValueType.SYSTEMOPTION)) { // lookup value String internalKey; if (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION) { // custom option: we do not differentiate by // fieldID_parameterCode between // the different custom option fields because if // a "not compatible" (assigned to naother list) // optionsettings is already present it will be // leaved as it is // but the options should be set to the imported // values independently of the optionsettings internalKey = ExchangeFieldNames.OPTION; } else { // system option internalKey = MergeUtil.mergeKey(internalFieldID, parameterCode); ILookup lookup = (ILookup) internalFieldTypeRT; Integer dropdownFieldKey = lookup.getDropDownMapFieldKey(internalFieldID); if (!dropdownFieldKey.equals(internalFieldID)) { internalKey = MergeUtil.mergeKey(dropdownFieldKey, parameterCode); } } Map<Integer, Integer> dropDownMap = dropDownMatcherMap.get(internalKey); if (dropDownMap != null) { Integer externalDropDown = null; if (internalFieldTypeRT.isMultipleValues()) { // custom select List<String> multipleValuesList = (List<String>) exchangeAttribut; Integer[] internalDropDownArr = null; if (multipleValuesList != null) { internalDropDownArr = new Integer[multipleValuesList.size()]; Iterator<String> itrMultiple = multipleValuesList.iterator(); int i = 0; while (itrMultiple.hasNext()) { String externalStringValue = itrMultiple.next(); Integer parsedExternalDropDownValue = (Integer) internalFieldTypeRT .parseISOValue(externalStringValue); Integer internalDropDownValue = dropDownMap .get(parsedExternalDropDownValue); internalDropDownArr[i++] = internalDropDownValue; } } exchangeAttribut = internalDropDownArr; } else { // system select externalDropDown = (Integer) internalFieldTypeRT .parseISOValue(exchangeAttribut); exchangeAttribut = dropDownMap.get(externalDropDown); } internalWorkItemBean.setAttribute(internalFieldID, parameterCode, exchangeAttribut); } } else { // direct value internalWorkItemBean.setAttribute(internalFieldID, parameterCode, internalFieldTypeRT.parseISOValue(exchangeAttribut)); if (internalFieldTypeRT.getValueType() == ValueType.LONGTEXT) { String longText = (String) exchangeAttribut; if (longText != null) { List<Integer> issueIDsInNew = TagReplacer .gatherIssueLinks(new StringBuilder(longText)); // if the description contains issue links // the workItem should be post-processed // later // now it contains the wrong (external) // issue links // mark it as post processing needed if (!issueIDsInNew.isEmpty()) { externalWorkItemUuidsWithLink.add(externalUUID); } } } } } } else { if (SystemFields.INTEGER_SUPERIORWORKITEM.equals(externalFieldID)) { // if the parentID is specified the workItem should be // post-processed later // the external parentID is not set at all because by // saving the // issue it could cause foreign key problems // mark it as post processing needed Object exchangeAttribut = actualFieldValuesMap.get(externalKey); if (exchangeAttribut != null) { externalWorkItemUuidsWithLink.add(externalUUID); } } } } List<ErrorData> workItemErrorList = new ArrayList<ErrorData>(); if (isNew) { addOldValueAsCustomAttribute(workItemContext, externalWorkItemID.toString()); } boolean saveNeeded = FieldsManagerRT.performSave(workItemContext, workItemErrorList, false, false/*, false*/); if (workItemErrorList.isEmpty()) { if (saveNeeded) { LOGGER.info("WorkItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemBean.getObjectID() + " was " + (isNew ? "created" : "updated")); if (isNew) { result = CREATED; externalWorkItemNrToInternalWkItemNr.put(internalWorkItemBean.getObjectID(), externalWorkItemID + "," + internalWorkItemBean.getSynopsis()); } else { result = UPGRADED; } } } else { ImportExceptionList importExceptionList = new ImportExceptionList(); importExceptionList.setErrorDataList(workItemErrorList); throw importExceptionList; } } // add the workItemIDs to the matcherMap Integer internalWorkItemID = internalWorkItemBean.getObjectID(); if (internalWorkItemID == null) { return result; } Map<Integer, Integer> workItemIDsMatcherMap = dropDownMatcherMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_ISSUENO, null)); workItemIDsMatcherMap.put(externalWorkItemID, internalWorkItemID); Map<Integer, Integer> personMap = dropDownMatcherMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_PERSON, null)); /** * add history values */ Set<Integer> pseudoHistoryFields = HistoryLoaderBL.getPseudoHistoryFields(); List<ExchangeHistoryTransactionEntry> historyValuesList = exchangeWorkItem.getHistoryValues(); if (historyValuesList != null) { for (ExchangeHistoryTransactionEntry exchangeHistoryTransactionEntry : historyValuesList) { String externalTransactionUuid = exchangeHistoryTransactionEntry.getUuid(); String strChangedAt = exchangeHistoryTransactionEntry.getChangedAt(); Date changedAt = null; if (strChangedAt != null) { changedAt = DateTimeUtils.getInstance().parseISODateTime(strChangedAt); } List<ExchangeHistoryFieldEntry> externalFieldChanges = exchangeHistoryTransactionEntry .getHistoryFieldChanges(); if (externalFieldChanges != null) { if (transactionUuidsForInternalWorkitem != null && transactionUuidsForInternalWorkitem.contains(externalTransactionUuid)) { // found external and internal transaction with the same // uuid: // the only possible modification is by the comment // in the reportBeanWithHistory only the comments are // loaded for (ExchangeHistoryFieldEntry exchangeHistoryFieldEntry : externalFieldChanges) { Integer fieldID = new Integer(exchangeHistoryFieldEntry.getFieldID()); if (fieldID.equals(SystemFields.INTEGER_COMMENT)) { List<HistoryValues> internalComments = reportBeanWithHistory.getComments(); if (internalComments != null) { Iterator<HistoryValues> itrInternalComments = internalComments.iterator(); while (itrInternalComments.hasNext()) { HistoryValues historyValues = itrInternalComments.next(); if (historyValues != null) { String internalComment = historyValues.getNewShowValue(); Integer internalTimesEdited = historyValues.getTimesEdited(); String internalTransactionUUID = historyValues.getTransactionUuid(); if (externalTransactionUuid.equals(internalTransactionUUID)) { String externalComment = exchangeHistoryFieldEntry .getNewStringValue(); String strExternalTimesEdited = exchangeHistoryFieldEntry .getTimesEdited(); Integer externalTimesEdited = null; if (strExternalTimesEdited != null) { externalTimesEdited = new Integer(strExternalTimesEdited); } if (EqualUtils.notEqual(internalComment, externalComment) && externalTimesEdited != null && (internalTimesEdited == null || externalTimesEdited .intValue() > internalTimesEdited.intValue())) { try { HistoryDAOUtils.updateFieldChange( FieldChangeBL.loadByPrimaryKey( historyValues.getObjectID()), externalComment, ValueType.LONGTEXT); } catch (ItemPersisterException e) { LOGGER.warn( "Updating the comment for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID + ", historyTransactionID " + internalTransactionUUID + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } LOGGER.info("Comment modified for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID); if (externalComment != null) { List<Integer> issueIDsInComment = TagReplacer .gatherIssueLinks( new StringBuilder(externalComment)); if (!issueIDsInComment.isEmpty()) { // remember the // transactionUUID // for the comment externalTransactionUuidsWithLink .add(externalTransactionUuid); } } } } } } } } } } else { // the external transaction uuid is not found in the // internal history Integer externalPerson = new Integer(exchangeHistoryTransactionEntry.getChangedBy()); Integer historyTransactionID = HistoryTransactionBL.saveHistoryTransaction( internalWorkItemID, personMap.get(externalPerson), changedAt, externalTransactionUuid); if (historyTransactionID != null) { for (ExchangeHistoryFieldEntry exchangeHistoryFieldEntry : externalFieldChanges) { Integer externalFieldID = new Integer(exchangeHistoryFieldEntry.getFieldID()); Integer internalFieldID; if (fieldsMatcherMap.get(externalFieldID) != null) { // replace the external fieldID with the // internal fieldID for the custom fields internalFieldID = fieldsMatcherMap.get(externalFieldID); } else { // for the system fields the internal and // external fieldIDs are the same and does // not appear in this map internalFieldID = externalFieldID; } Integer parameterCode = null; if (exchangeHistoryFieldEntry.getParameterCode() != null) { parameterCode = new Integer(exchangeHistoryFieldEntry.getParameterCode()); } IFieldTypeRT internalFieldTypeRT = null; if (pseudoHistoryFields.contains(internalFieldID)) { internalFieldTypeRT = FieldTypeManager .getFieldTypeRT(SystemFields.INTEGER_DESCRIPTION, null); } else { internalFieldTypeRT = FieldTypeManager.getFieldTypeRT(internalFieldID, parameterCode); } if (internalFieldTypeRT != null) { String newStringValue = exchangeHistoryFieldEntry.getNewStringValue(); Object newValue = internalFieldTypeRT.parseISOValue(newStringValue); String oldStringValue = exchangeHistoryFieldEntry.getOldStringValue(); Object oldValue = internalFieldTypeRT.parseISOValue(oldStringValue); if (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION || (internalFieldTypeRT.getValueType() == ValueType.SYSTEMOPTION && !SystemFields.INTEGER_SUPERIORWORKITEM .equals(externalFieldID))) { // exclude the parent item because it // will be set at the end String internalKey; if (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION) { // custom option: we do not // differentiate by // fieldID_parameterCode between // the different custom option // fields because if a // "not compatible" (assigned to // naother list) // optionsettings is already present // it will be leaved as it is // but the options should be set to // the imported values independently // of the optionsettings internalKey = ExchangeFieldNames.OPTION; } else { /* * if * (SystemFields.INTEGER_ISSUENO.equals * (externalFieldID) || * SystemFields. * INTEGER_SUPERIORWORKITEM * .equals(externalFieldID)) { * //superior workitem explicit * history: //TODO it does not work * if the parent is not yet added in * the dropDownMatcherMap * internalKey = * MergeUtil.mergeKey(SystemFields * .INTEGER_ISSUENO, parameterCode); * } else { */ // system option internalKey = MergeUtil.mergeKey(internalFieldID, parameterCode); ILookup lookup = (ILookup) internalFieldTypeRT; Integer dropdownFieldKey = lookup .getDropDownMapFieldKey(internalFieldID); if (!dropdownFieldKey.equals(internalFieldID)) { internalKey = MergeUtil.mergeKey(dropdownFieldKey, parameterCode); } // } } // the history values are always stored // one by one (no multiple values as in // actual values) Map<Integer, Integer> dropDownMap = dropDownMatcherMap.get(internalKey); if (dropDownMap != null) { newValue = dropDownMap.get(newValue); oldValue = dropDownMap.get(oldValue); } } // save the fieldChange try { HistoryDAOUtils.insertFieldChange(internalFieldID, parameterCode, historyTransactionID, newValue, oldValue, internalFieldTypeRT.getValueType(), internalFieldTypeRT.getSystemOptionType()); } catch (ItemPersisterException e) { LOGGER.warn("Inserting the fieldChange for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID + " for field " + internalFieldID + ", historyTransactionID " + historyTransactionID + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } LOGGER.debug("History added for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID + " and field " + internalFieldID); // remember the transactionUUIDs for the // descriptions/comments/common // history/other long texts // which contain issueIDs because they // should be replaced later if (internalFieldTypeRT.getValueType() == ValueType.LONGTEXT) { if (newStringValue != null) { List<Integer> issueIDsInNew = TagReplacer .gatherIssueLinks(new StringBuilder(newStringValue)); if (!issueIDsInNew.isEmpty()) { externalTransactionUuidsWithLink.add(externalTransactionUuid); } else { if (oldStringValue != null) { List<Integer> issueIDsInOld = TagReplacer .gatherIssueLinks(new StringBuilder(oldStringValue)); if (!issueIDsInOld.isEmpty()) { externalTransactionUuidsWithLink .add(externalTransactionUuid); } } } } } else { // explicit history for parent // remember the transactionUUIDs with // parentIDs because they should be // replaced later // now the wrong (external) value is // saved but it does not cause foreign // key problems because // the system fields from history are // not linked with foreign keys if (SystemFields.INTEGER_SUPERIORWORKITEM.equals(externalFieldID)) { if (newValue != null) { externalTransactionUuidsWithLink.add(externalTransactionUuid); } } } } } } } } } } /** * add consultants/informants */ addRaciRole(exchangeWorkItem.getConsultedList(), reportBeanWithHistory.getConsultedList(), internalWorkItemID, RaciRole.CONSULTANT, personMap); addRaciRole(exchangeWorkItem.getInformedList(), reportBeanWithHistory.getInformedList(), internalWorkItemID, RaciRole.INFORMANT, personMap); /** * add budget values */ List<TBudgetBean> externalBudgetBeanList = exchangeWorkItem.getBudgetBeanList(); List<TBudgetBean> internalBudgetBeanList = reportBeanWithHistory.getBudgetHistory(); Map<String, TBudgetBean> internalBudgetBeanMap = new HashMap<String, TBudgetBean>(); if (externalBudgetBeanList != null) { Date lastBudget = null; if (internalBudgetBeanList != null) { for (TBudgetBean budgetBean : internalBudgetBeanList) { if (lastBudget == null || lastBudget.before(budgetBean.getLastEdit())) { lastBudget = budgetBean.getLastEdit(); } internalBudgetBeanMap.put(budgetBean.getUuid(), budgetBean); } } for (TBudgetBean externalBudgetBean : externalBudgetBeanList) { String uuid = externalBudgetBean.getUuid(); TBudgetBean internalBudgetBean = internalBudgetBeanMap.get(uuid); if (internalBudgetBean == null) { // it is a new object externalBudgetBean.setObjectID(null); externalBudgetBean.saveBean(externalBudgetBean, dropDownMatcherMap); LOGGER.info("Budget added"); if (externalIsMoreRecent(externalBudgetBean.getLastEdit(), lastBudget, "budget", externalBudgetBean.getObjectID())) { lastBudget = externalBudgetBean.getLastEdit(); // actualize the computed values table if more recent ComputedValueBL.computeBudgetOrPlan(externalBudgetBean); LOGGER.info("Budget recomputed"); } } } } /** * add plan values */ List<TBudgetBean> externalPlanBeanList = exchangeWorkItem.getPlannedValueBeanList(); List<TBudgetBean> internalPlanBeanList = reportBeanWithHistory.getPlannedValueHistory(); Map<String, TBudgetBean> internalPlanBeanMap = new HashMap<String, TBudgetBean>(); if (externalPlanBeanList != null) { Date lastBudget = null; if (internalPlanBeanList != null) { for (TBudgetBean budgetBean : internalPlanBeanList) { if (lastBudget == null || lastBudget.before(budgetBean.getLastEdit())) { lastBudget = budgetBean.getLastEdit(); } internalPlanBeanMap.put(budgetBean.getUuid(), budgetBean); } } for (TBudgetBean externalBudgetBean : externalPlanBeanList) { String uuid = externalBudgetBean.getUuid(); TBudgetBean internalBudgetBean = internalPlanBeanMap.get(uuid); if (internalBudgetBean == null) { // it is a new object externalBudgetBean.setObjectID(null); externalBudgetBean.saveBean(externalBudgetBean, dropDownMatcherMap); LOGGER.info("Plan added"); if (externalIsMoreRecent(externalBudgetBean.getLastEdit(), lastBudget, "plan", externalBudgetBean.getObjectID())) { lastBudget = externalBudgetBean.getLastEdit(); // actualize the computed values table if more recent ComputedValueBL.computeBudgetOrPlan(externalBudgetBean); LOGGER.info("Plan recomputed"); } } } } /** * add/modify remaining budget */ TActualEstimatedBudgetBean externalRemainingBudget = exchangeWorkItem.getActualEstimatedBudgetBean(); TActualEstimatedBudgetBean internalRemainingBudget = reportBeanWithHistory.getActualEstimatedBudgetBean(); if (externalRemainingBudget != null) { if (internalRemainingBudget == null) { // it is a new object externalRemainingBudget.setObjectID(null); externalRemainingBudget.saveBean(externalRemainingBudget, dropDownMatcherMap); LOGGER.info("Remaining budget added"); } else { // remaining budget found if (externalIsMoreRecent(externalRemainingBudget.getLastEdit(), internalRemainingBudget.getLastEdit(), "remaining budget", externalRemainingBudget.getObjectID())) { externalRemainingBudget.replaceLookup(dropDownMatcherMap); if (externalRemainingBudget.hasChanged(internalRemainingBudget)) { // modify if changed externalRemainingBudget.copy(internalRemainingBudget); RemainingPlanBL.save(internalRemainingBudget); LOGGER.info("Remaining budget modified"); } } } } /** * add/modify cost values */ List<TCostBean> externalCostBeanList = exchangeWorkItem.getExpenseBeanList(); List<TCostBean> internalCostBeanList = reportBeanWithHistory.getCosts(); Map<String, ISerializableLabelBean> internalCostBeanMap = new HashMap<String, ISerializableLabelBean>(); if (externalCostBeanList != null) { if (internalCostBeanList != null) { internalCostBeanMap = GeneralUtils.createUUIDMapFromSerializableBean((List) internalCostBeanList); } Iterator<TCostBean> itrExternalCostBeans = externalCostBeanList.iterator(); while (itrExternalCostBeans.hasNext()) { TCostBean externalCostBean = itrExternalCostBeans.next(); String uuid = externalCostBean.getUuid(); TCostBean internalCostBean = (TCostBean) internalCostBeanMap.get(uuid); if (internalCostBean == null) { // it is a new object externalCostBean.setObjectID(null); externalCostBean.saveBean(externalCostBean, dropDownMatcherMap); // TODO do not recompute always but only the last for each // person ComputedValueBL.computeExpenses(externalCostBean.getWorkitem(), externalCostBean.getPerson()); LOGGER.info("Expense added and recomputed"); } else { // cost found if (externalIsMoreRecent(externalCostBean.getLastEdit(), internalCostBean.getLastEdit(), "expense", externalCostBean.getObjectID())) { externalCostBean.replaceLookup(dropDownMatcherMap); if (externalCostBean.hasChanged(internalCostBean)) { // modify if changed externalCostBean.copy(internalCostBean); ExpenseBL.saveCostBean(internalCostBean); // TODO do not recompute always but only the last // for each person ComputedValueBL.computeExpenses(internalCostBean.getWorkitem(), internalCostBean.getPerson()); LOGGER.info("Expense modified and recomputed"); } } } } } /** * add/modify the attachments */ List<TAttachmentBean> externalAttachmentBeanList = exchangeWorkItem.getAttachmentBeanList(); List<TAttachmentBean> internalAttachmentBeanList = reportBeanWithHistory.getAttachments(); if (externalAttachmentBeanList != null) { Map<String, ISerializableLabelBean> internalAttachmentBeanMap = new HashMap<String, ISerializableLabelBean>(); if (internalAttachmentBeanList != null) { internalAttachmentBeanMap = GeneralUtils .createUUIDMapFromSerializableBean((List) internalAttachmentBeanList); } Iterator<TAttachmentBean> itrExternalAttachmentBeans = externalAttachmentBeanList.iterator(); while (itrExternalAttachmentBeans.hasNext()) { TAttachmentBean externalAttachmentBean = itrExternalAttachmentBeans.next(); String uuid = externalAttachmentBean.getUuid(); TAttachmentBean internalAttachmentBean = (TAttachmentBean) internalAttachmentBeanMap.get(uuid); boolean foundMatch = false; if (internalAttachmentBean == null) { // not found by uuid, try by considerAsSame if (internalAttachmentBeanList != null) { Iterator<TAttachmentBean> tAttachmentBean = internalAttachmentBeanList.iterator(); while (tAttachmentBean.hasNext()) { internalAttachmentBean = tAttachmentBean.next(); if (externalAttachmentBean.considerAsSame(internalAttachmentBean, dropDownMatcherMap)) { foundMatch = true; break; } } } } else { foundMatch = true; } if (foundMatch) { // attachment found if (internalAttachmentBean != null && externalIsMoreRecent(externalAttachmentBean.getLastEdit(), internalAttachmentBean.getLastEdit(), "attachment", externalAttachmentBean.getObjectID())) { if (externalAttachmentBean.hasChanged(internalAttachmentBean)) { internalAttachmentBean.setDescription(externalAttachmentBean.getDescription()); internalAttachmentBean.setLastEdit(externalAttachmentBean.getLastEdit()); AttachBL.save(internalAttachmentBean); LOGGER.info("Attachment description modified: " + externalAttachmentBean.getFileName()); } } } else { // new attachment Integer internalAttachmentNo; Integer externalAttachmentNo = externalAttachmentBean.getObjectID(); externalAttachmentBean.setObjectID(null); internalAttachmentNo = externalAttachmentBean.saveBean(externalAttachmentBean, dropDownMatcherMap); LOGGER.info("Attachment added: " + externalAttachmentBean.getFileName()); String attachmentsPath = AttachBL.getAttachDirBase(); String tempDirectoryPath = attachmentsPath + File.separator + AttachBL.tmpAttachments; String workItemAttachmentPath = attachmentsPath + File.separator + internalWorkItemID; // add also the files File attachmentFile = new File(tempDirectoryPath, AttachBL.getFileNameAttachment(externalAttachmentNo, externalWorkItemID)); // parent directory File workItemAttachmentFile = new File(workItemAttachmentPath); if (!workItemAttachmentFile.exists()) { workItemAttachmentFile.mkdirs(); } // Move file to new directory boolean success = attachmentFile.renameTo(new File(workItemAttachmentFile, AttachBL.getFileNameAttachment(internalAttachmentNo, externalWorkItemID))); if (!success) { LOGGER.error("Moving the file " + externalAttachmentBean.getFileName() + " failed"); } } } } return result; }
From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java
@SuppressWarnings("unchecked") private static void write(boolean useTemplate, Workbook workbook, OutputStream outputStream, ExcelWriteSheetProcessor<?>... sheetProcessors) { for (@SuppressWarnings("rawtypes") ExcelWriteSheetProcessor sheetProcessor : sheetProcessors) { @SuppressWarnings("rawtypes") ExcelWriteContext context = new ExcelWriteContext(); try {/*from w w w .j a va 2s . co m*/ if (sheetProcessor == null) { continue; } String sheetName = sheetProcessor.getSheetName(); Integer sheetIndex = sheetProcessor.getSheetIndex(); Sheet sheet = null; if (sheetProcessor.getTemplateStartRowIndex() == null && sheetProcessor.getTemplateEndRowIndex() == null) { sheetProcessor.setTemplateRows(sheetProcessor.getStartRowIndex(), sheetProcessor.getStartRowIndex()); } // sheetName priority, if (useTemplate) { if (sheetName != null) { try { sheet = workbook.getSheet(sheetName); } catch (IllegalArgumentException e) { // ignore } if (sheet != null && sheetIndex != null && !sheetIndex.equals(workbook.getSheetIndex(sheet))) { throw new IllegalArgumentException( "sheetName[" + sheetName + "] and sheetIndex[" + sheetIndex + "] not match."); } } else if (sheetIndex != null) { try { sheet = workbook.getSheetAt(sheetIndex); } catch (IllegalArgumentException e) { // ignore } } else { throw new IllegalArgumentException("sheetName or sheetIndex can't be null"); } if (sheet == null) { ExcelWriteException e = new ExcelWriteException( "Sheet Not Found Exception. for sheet name:" + sheetName); e.setCode(ExcelWriteException.CODE_OF_SHEET_NOT_EXSIT); throw e; } } else { if (sheetName != null) { sheet = workbook.getSheet(sheetName); if (sheet != null) { if (sheetIndex != null && !sheetIndex.equals(workbook.getSheetIndex(sheet))) { throw new IllegalArgumentException("sheetName[" + sheetName + "] and sheetIndex[" + sheetIndex + "] not match."); } } else { sheet = workbook.createSheet(sheetName); if (sheetIndex != null) { workbook.setSheetOrder(sheetName, sheetIndex); } } } else if (sheetIndex != null) { sheet = workbook.createSheet(); workbook.setSheetOrder(sheet.getSheetName(), sheetIndex); } else { throw new IllegalArgumentException("sheetName or sheetIndex can't be null"); } } if (sheetIndex == null) { sheetIndex = workbook.getSheetIndex(sheet); } if (sheetName == null) { sheetName = sheet.getSheetName(); } // proc sheet context.setCurSheet(sheet); context.setCurSheetIndex(sheetIndex); context.setCurSheetName(sheet.getSheetName()); context.setCurRow(null); context.setCurRowIndex(null); context.setCurCell(null); context.setCurColIndex(null); // beforeProcess sheetProcessor.beforeProcess(context); // write head writeHead(useTemplate, sheet, sheetProcessor); // sheet ExcelProcessControllerImpl controller = new ExcelProcessControllerImpl(); int writeRowIndex = sheetProcessor.getStartRowIndex(); boolean isBreak = false; Map<Integer, InnerRow> cacheForTemplateRow = new HashMap<Integer, InnerRow>(); List<?> dataList = sheetProcessor.getDataList(); // if (dataList != null && !dataList.isEmpty()) { for (Object rowData : dataList) { // proc row Row row = sheet.getRow(writeRowIndex); if (row == null) { row = sheet.createRow(writeRowIndex); } InnerRow templateRow = getTemplateRow(cacheForTemplateRow, sheet, sheetProcessor, writeRowIndex); if (templateRow != null) { row.setHeight(templateRow.getHeight()); row.setHeightInPoints(templateRow.getHeightInPoints()); row.setRowStyle(templateRow.getRowStyle()); row.setZeroHeight(templateRow.isZeroHeight()); } context.setCurRow(row); context.setCurRowIndex(writeRowIndex); context.setCurColIndex(null); context.setCurCell(null); // try { controller.reset(); if (sheetProcessor.getRowProcessor() != null) { sheetProcessor.getRowProcessor().process(controller, context, rowData, row); } if (!controller.isDoSkip()) { writeRow(context, templateRow, row, rowData, sheetProcessor); writeRowIndex++; } if (controller.isDoBreak()) { isBreak = true; break; } } catch (RuntimeException e) { if (e instanceof ExcelWriteException) { ExcelWriteException ewe = (ExcelWriteException) e; // ef.setColIndex(null); user may want to set this value, ewe.setRowIndex(writeRowIndex); throw ewe; } else { ExcelWriteException ewe = new ExcelWriteException(e); ewe.setColIndex(null); ewe.setCode(ExcelWriteException.CODE_OF_PROCESS_EXCEPTION); ewe.setRowIndex(writeRowIndex); throw ewe; } } } if (isBreak) { break; } } if (sheetProcessor.getTemplateStartRowIndex() != null && sheetProcessor.getTemplateEndRowIndex() != null) { writeDataValidations(sheet, sheetProcessor); writeStyleAfterFinish(useTemplate, sheet, sheetProcessor); } } catch (RuntimeException e) { sheetProcessor.onException(context, e); } finally { sheetProcessor.afterProcess(context); } } try { workbook.write(outputStream); } catch (IOException e) { throw new RuntimeException(e); } }