List of usage examples for java.util Hashtable get
@SuppressWarnings("unchecked") public synchronized V get(Object key)
From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java
private void parseEntites(KNXConnector knxConnector, ObjectBroker objectBroker, Hashtable<String, EntityImpl> entityById, Hashtable<String, DatapointImpl> datapointById, NetworkImpl n, Hashtable<String, String> resourceById, Hashtable<String, String> groupAddressByDatapointID, boolean enableGroupComm, boolean enableHistories) { for (int entityIdx = 0; entityIdx < sizeOfConfiguration( devicesConfig.getProperty("entities.entity[@id]")); entityIdx++) { // Entity HierarchicalConfiguration entityConfig = devicesConfig .configurationAt("entities.entity(" + entityIdx + ")"); String entityId = entityConfig.getString("[@id]"); String entityName = arrayToString(entityConfig.getStringArray("[@name]")); String entityDescription = arrayToString(entityConfig.getStringArray("[@description]")); String entityOrderNumber = entityConfig.getString("[@orderNumber]"); String entityManufacturerId = entityConfig.getString("[@manufacturerId]"); EntityImpl entity = new EntityImpl(entityId, entityName, entityDescription, resourceById.get(entityManufacturerId), entityOrderNumber); entityById.put(entityId, entity); n.getEntities().addEntity(entity); objectBroker.addObj(entity, true); // Translations for (int transIdx = 0; transIdx < sizeOfConfiguration( entityConfig.getProperty("translations.translation[@language]")); transIdx++) { HierarchicalConfiguration transConfig = entityConfig .configurationAt("translations.translation(" + transIdx + ")"); String language = transConfig.getString("[@language]"); String attribute = transConfig.getString("[@attribute]"); String value = arrayToString(transConfig.getStringArray("[@value]")); try { entity.addTranslation(language, attribute, value); } catch (Exception e) { log.warning(e.getMessage()); }/*from w w w . j a v a 2 s.c o m*/ } // DPs for (int datapointIdx = 0; datapointIdx < sizeOfConfiguration( entityConfig.getProperty("datapoints.datapoint[@id]")); datapointIdx++) { HierarchicalConfiguration datapointConfig = entityConfig .configurationAt("datapoints.datapoint(" + datapointIdx + ")"); String dataPointName = arrayToString(datapointConfig.getStringArray("[@name]")); String dataPointTypeIds = datapointConfig.getString("[@datapointTypeIds]"); String dataPointId = datapointConfig.getString("[@id]"); String dataPointDescription = arrayToString(datapointConfig.getStringArray("[@description]")); String dataPointWriteFlag = datapointConfig.getString("[@writeFlag]"); String dataPointReadFlag = datapointConfig.getString("[@readFlag]"); // String dataPointPriority = datapointConfig.getString("[@priority]"); // String dataPointCommunicationFlag = datapointConfig.getString("[@communicationFlag]"); // String dataPointReadOnInitFlag = datapointConfig.getString("[@readOnInitFlag]"); // String dataPointTransmitFlag = datapointConfig.getString("[@transmitFlag]"); // String updateFlag = datapointConfig.getString("[@updateFlag]"); // use only the first DPTS if (dataPointTypeIds.indexOf(" ") >= 0) { dataPointTypeIds = dataPointTypeIds.substring(0, dataPointTypeIds.indexOf(" ")); } log.info("Found data point type id: " + dataPointTypeIds); String clazzName = "at.ac.tuwien.auto.iotsys.gateway.obix.objects.knx.datapoint.impl." + dataPointTypeIds.replace('-', '_') + "_ImplKnx"; Class<?> clazz = null; try { log.info("Loading: " + clazzName); clazz = Class.forName(clazzName); } catch (ClassNotFoundException e) { log.warning(clazzName + " not found. Cannot instantiate according sub data point type. Trying fallback to generic main type."); int firstIndexOf = dataPointTypeIds.indexOf('-'); int secondIndexOf = dataPointTypeIds.indexOf('-', firstIndexOf + 1); clazzName = "at.ac.tuwien.auto.iotsys.gateway.obix.objects.knx.datapoint.impl." + "DPT_" + dataPointTypeIds.substring(firstIndexOf + 1, secondIndexOf) + "_ImplKnx"; // try { log.info("Loading: " + clazzName); clazz = Class.forName(clazzName); } catch (ClassNotFoundException e1) { e1.printStackTrace(); log.warning(clazzName + " not found. Cannot instantiate according main data point type."); } } try { if (clazz != null) { Constructor<?> constructor = clazz.getConstructor(KNXConnector.class, DataPointInit.class); Object[] object = new Object[2]; object[0] = knxConnector; DataPointInit dptInit = new DataPointInit(); dptInit.setDisplay(dataPointDescription); dptInit.setDisplayName(dataPointName); dptInit.setReadable( EnumsImpl.getInstance().getEnum(EnumEnabled.HREF).getBool(dataPointReadFlag)); dptInit.setName(dataPointId); dptInit.setGroupAddress( new GroupAddress(Integer.parseInt(groupAddressByDatapointID.get(dataPointId)))); dptInit.setWritable( EnumsImpl.getInstance().getEnum(EnumEnabled.HREF).getBool(dataPointWriteFlag)); object[1] = dptInit; DatapointImpl dataPoint = (DatapointImpl) constructor.newInstance(object); datapointById.put(dataPointId, dataPoint); entity.addDatapoint(dataPoint); if (enableGroupComm) objectBroker.enableGroupComm(dataPoint); if (enableHistories) objectBroker.addHistoryToDatapoints(dataPoint); objectBroker.addObj(dataPoint, true); // Search for child "value" Obj dpValue = dataPoint.get("value"); if (dpValue != null) { dpValue.setDisplayName(dataPointDescription); } // Translations (DP) for (int transIdx = 0; transIdx < sizeOfConfiguration( datapointConfig.getProperty("translations.translation[@language]")); transIdx++) { HierarchicalConfiguration transConfig = datapointConfig .configurationAt("translations.translation(" + transIdx + ")"); String language = transConfig.getString("[@language]"); String attribute = transConfig.getString("[@attribute]"); String value = arrayToString(transConfig.getStringArray("[@value]")); try { dataPoint.addTranslation(language, attribute, value); // translation for DisplayName of value if (attribute.toLowerCase().trim().equals("description") && dpValue != null) { dpValue.addTranslation(language, TranslationAttribute.displayName, value); } } catch (Exception e) { log.warning(e.getMessage()); } } } } catch (NoSuchMethodException e) { log.warning(clazzName + " no such method. Cannot instantiate according datapoint."); } catch (SecurityException e) { log.warning(clazzName + " security exception. Cannot instantiate according datapoint."); } catch (InstantiationException e) { log.warning(clazzName + " instantiation exception. Cannot instantiate according datapoint."); } catch (IllegalAccessException e) { log.warning(clazzName + " illegal access exception. Cannot instantiate according datapoint."); } catch (IllegalArgumentException e) { log.warning(clazzName + " illegal argument exception. Cannot instantiate according datapoint."); e.printStackTrace(); } catch (InvocationTargetException e) { log.warning( clazzName + " invocation target exception. Cannot instantiate according datapoint."); e.printStackTrace(); } } } }
From source file:oscar.dms.actions.DmsInboxManageAction.java
public ActionForward prepareForContentPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/*from w w w .j a v a2s . com*/ HttpSession session = request.getSession(); try { if (session.getAttribute("userrole") == null) response.sendRedirect("../logout.jsp"); } catch (Exception e) { logger.error("Error", e); } // can't use userrole from session, because it changes if provider A search for provider B's documents // oscar.oscarMDS.data.MDSResultsData mDSData = new oscar.oscarMDS.data.MDSResultsData(); CommonLabResultData comLab = new CommonLabResultData(); // String providerNo = request.getParameter("providerNo"); String providerNo = (String) session.getAttribute("user"); String searchProviderNo = request.getParameter("searchProviderNo"); String ackStatus = request.getParameter("status"); String demographicNo = request.getParameter("demographicNo"); // used when searching for labs by patient instead of provider String scannedDocStatus = request.getParameter("scannedDocument"); Integer page = 0; try { page = Integer.parseInt(request.getParameter("page")); if (page > 0) { page--; } } catch (NumberFormatException nfe) { page = 0; } Integer pageSize = 20; try { String tmp = request.getParameter("pageSize"); pageSize = Integer.parseInt(tmp); } catch (NumberFormatException nfe) { pageSize = 20; } scannedDocStatus = "I"; String startDateStr = request.getParameter("startDate"); String endDateStr = request.getParameter("endDate"); String view = request.getParameter("view"); if (view == null || "".equals(view)) { view = "all"; } boolean mixLabsAndDocs = "normal".equals(view) || "all".equals(view); Date startDate = null; Date endDate = null; try { if (startDateStr != null && startDateStr.length() > 0) { startDateStr = startDateStr.trim(); startDate = UtilDateUtilities.StringToDate(startDateStr); } if (endDateStr != null && endDateStr.length() > 0) { endDateStr = endDateStr.trim(); endDate = UtilDateUtilities.StringToDate(endDateStr); } } catch (Exception e) { startDate = null; endDate = null; } Boolean isAbnormal = null; if ("abnormal".equals(view)) isAbnormal = new Boolean(true); if ("normal".equals(view)) isAbnormal = new Boolean(false); if (ackStatus == null) { ackStatus = "N"; } // default to new labs only if (providerNo == null) { providerNo = ""; } if (searchProviderNo == null) { searchProviderNo = providerNo; } String roleName = ""; List<SecUserRole> roles = secUserRoleDao.getUserRoles(searchProviderNo); for (SecUserRole r : roles) { if (r != null) { if (roleName.length() == 0) { roleName = r.getRoleName(); } else { roleName += "," + r.getRoleName(); } } } roleName += "," + searchProviderNo; // mDSData.populateMDSResultsData2(searchProviderNo, demographicNo, request.getParameter("fname"), request.getParameter("lname"), request.getParameter("hnum"), ackStatus); // HashMap<String,String> docQueue=comLab.getDocumentQueueLinks(); List<QueueDocumentLink> qd = queueDocumentLinkDAO.getQueueDocLinks(); HashMap<String, String> docQueue = new HashMap(); for (QueueDocumentLink qdl : qd) { Integer i = qdl.getDocId(); Integer n = qdl.getQueueId(); docQueue.put(i.toString(), n.toString()); } InboxResultsDao inboxResultsDao = (InboxResultsDao) SpringUtils.getBean("inboxResultsDao"); String patientFirstName = request.getParameter("fname"); String patientLastName = request.getParameter("lname"); String patientHealthNumber = request.getParameter("hnum"); ArrayList<LabResultData> labdocs = new ArrayList<LabResultData>(); if (!"labs".equals(view) && !"abnormal".equals(view)) { labdocs = inboxResultsDao.populateDocumentResultsData(searchProviderNo, demographicNo, patientFirstName, patientLastName, patientHealthNumber, ackStatus, true, page, pageSize, mixLabsAndDocs, isAbnormal); } if (!"documents".equals(view)) { labdocs.addAll(comLab.populateLabResultsData(searchProviderNo, demographicNo, patientFirstName, patientLastName, patientHealthNumber, ackStatus, scannedDocStatus, true, page, pageSize, mixLabsAndDocs, isAbnormal)); } labdocs = (ArrayList<LabResultData>) filterLabDocsForSuperSite(labdocs, providerNo); ArrayList<LabResultData> validlabdocs = new ArrayList<LabResultData>(); DocumentResultsDao documentResultsDao = (DocumentResultsDao) SpringUtils.getBean("documentResultsDao"); // check privilege for documents only for (LabResultData data : labdocs) { if (data.isDocument()) { String docid = data.getSegmentID(); String queueid = docQueue.get(docid); if (queueid != null) { queueid = queueid.trim(); int queueIdInt = Integer.parseInt(queueid); // if doc sent to default queue and no valid provider, do NOT include it if (queueIdInt == Queue.DEFAULT_QUEUE_ID && !documentResultsDao.isSentToValidProvider(docid) && isSegmentIDUnique(validlabdocs, data)) { // validlabdocs.add(data); } // if doc sent to default queue && valid provider, check if it's sent to this provider, if yes include it else if (queueIdInt == Queue.DEFAULT_QUEUE_ID && documentResultsDao.isSentToValidProvider(docid) && documentResultsDao.isSentToProvider(docid, searchProviderNo) && isSegmentIDUnique(validlabdocs, data)) { validlabdocs.add(data); } // if doc setn to non-default queue and valid provider, check if provider is in the queue or equal to the provider else if (queueIdInt != Queue.DEFAULT_QUEUE_ID && documentResultsDao.isSentToValidProvider(docid)) { Vector vec = OscarRoleObjectPrivilege.getPrivilegeProp("_queue." + queueid); if (OscarRoleObjectPrivilege.checkPrivilege(roleName, (Properties) vec.get(0), (Vector) vec.get(1)) || documentResultsDao.isSentToProvider(docid, searchProviderNo)) { // labs is in provider's queue,do nothing if (isSegmentIDUnique(validlabdocs, data)) { validlabdocs.add(data); } } } // if doc sent to non default queue and no valid provider, check if provider is in the non default queue else if (!queueid.equals(Queue.DEFAULT_QUEUE_ID) && !documentResultsDao.isSentToValidProvider(docid)) { Vector vec = OscarRoleObjectPrivilege.getPrivilegeProp("_queue." + queueid); if (OscarRoleObjectPrivilege.checkPrivilege(roleName, (Properties) vec.get(0), (Vector) vec.get(1))) { // labs is in provider's queue,do nothing if (isSegmentIDUnique(validlabdocs, data)) { validlabdocs.add(data); } } } } } else {// add lab if (isSegmentIDUnique(validlabdocs, data)) { validlabdocs.add(data); } } } // Find the oldest lab returned in labdocs, use that as the limit date for the HRM query Date oldestLab = null; Date newestLab = null; if (request.getParameter("newestDate") != null) { try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); newestLab = formatter.parse(request.getParameter("newestDate")); } catch (Exception e) { logger.error("Couldn't parse date + " + request.getParameter("newestDate"), e); } } for (LabResultData result : labdocs) { if (result != null && result.getDateObj() != null) { if (oldestLab == null || oldestLab.compareTo(result.getDateObj()) > 0) oldestLab = result.getDateObj(); if (request.getParameter("newestDate") != null && (newestLab == null || newestLab.compareTo(result.getDateObj()) < 0)) newestLab = result.getDateObj(); } } HRMResultsData hrmResult = new HRMResultsData(); Collection<LabResultData> hrmDocuments = hrmResult.populateHRMdocumentsResultsData(searchProviderNo, ackStatus, newestLab, oldestLab); if (oldestLab == null) { for (LabResultData hrmDocument : hrmDocuments) { if (oldestLab == null || (hrmDocument.getDateObj() != null && oldestLab.compareTo(hrmDocument.getDateObj()) > 0)) oldestLab = hrmDocument.getDateObj(); } } //labdocs is already filtered for super site access.. not just filter hrmDocuments hrmDocuments = filterLabDocsForSuperSite(hrmDocuments, providerNo); labdocs.addAll(hrmDocuments); Collections.sort(labdocs); HashMap<String, LabResultData> labMap = new HashMap<String, LabResultData>(); LinkedHashMap<String, ArrayList<String>> accessionMap = new LinkedHashMap<String, ArrayList<String>>(); int accessionNumCount = 0; for (LabResultData result : labdocs) { if (startDate != null && startDate.after(result.getDateObj())) { continue; } if (endDate != null && endDate.before(result.getDateObj())) { continue; } String segmentId = result.getSegmentID(); if (result.isDocument()) segmentId += "d"; else if (result.isHRM()) segmentId += "h"; labMap.put(segmentId, result); ArrayList<String> labNums = new ArrayList<String>(); if (result.accessionNumber == null || result.accessionNumber.equals("")) { labNums.add(segmentId); accessionNumCount++; accessionMap.put("noAccessionNum" + accessionNumCount + result.labType, labNums); } else if (!accessionMap.containsKey(result.accessionNumber + result.labType)) { labNums.add(segmentId); accessionMap.put(result.accessionNumber + result.labType, labNums); // Different MDS Labs may have the same accession Number if they are seperated // by two years. So accession numbers are limited to matching only if their // labs are within one year of eachother } else { labNums = accessionMap.get(result.accessionNumber + result.labType); boolean matchFlag = false; for (int j = 0; j < labNums.size(); j++) { LabResultData matchingResult = labMap.get(labNums.get(j)); Date dateA = result.getDateObj(); Date dateB = matchingResult.getDateObj(); int monthsBetween = 0; if (dateA == null || dateB == null) { monthsBetween = 5; } else if (dateA.before(dateB)) { monthsBetween = UtilDateUtilities.getNumMonths(dateA, dateB); } else { monthsBetween = UtilDateUtilities.getNumMonths(dateB, dateA); } if (monthsBetween < 4) { matchFlag = true; break; } } if (!matchFlag) { labNums.add(segmentId); accessionMap.put(result.accessionNumber + result.labType, labNums); } } } labdocs.clear(); for (ArrayList<String> labNums : accessionMap.values()) { // must sort through in reverse to keep the labs in the correct order for (int j = labNums.size() - 1; j >= 0; j--) { labdocs.add(labMap.get(labNums.get(j))); } } logger.debug("labdocs.size()=" + labdocs.size()); /* find all data for the index.jsp page */ Hashtable patientDocs = new Hashtable(); Hashtable patientIdNames = new Hashtable(); String patientIdNamesStr = ""; Hashtable docStatus = new Hashtable(); Hashtable docType = new Hashtable(); Hashtable<String, List<String>> ab_NormalDoc = new Hashtable(); for (int i = 0; i < labdocs.size(); i++) { LabResultData data = labdocs.get(i); List<String> segIDs = new ArrayList<String>(); String labPatientId = data.getLabPatientId(); if (labPatientId == null || labPatientId.equals("-1")) labPatientId = "-1"; if (data.isAbnormal()) { List<String> abns = ab_NormalDoc.get("abnormal"); if (abns == null) { abns = new ArrayList<String>(); abns.add(data.getSegmentID()); } else { abns.add(data.getSegmentID()); } ab_NormalDoc.put("abnormal", abns); } else { List<String> ns = ab_NormalDoc.get("normal"); if (ns == null) { ns = new ArrayList<String>(); ns.add(data.getSegmentID()); } else { ns.add(data.getSegmentID()); } ab_NormalDoc.put("normal", ns); } if (patientDocs.containsKey(labPatientId)) { segIDs = (List) patientDocs.get(labPatientId); segIDs.add(data.getSegmentID()); patientDocs.put(labPatientId, segIDs); } else { segIDs.add(data.getSegmentID()); patientDocs.put(labPatientId, segIDs); patientIdNames.put(labPatientId, data.patientName); patientIdNamesStr += ";" + labPatientId + "=" + data.patientName; } docStatus.put(data.getSegmentID(), data.getAcknowledgedStatus()); docType.put(data.getSegmentID(), data.labType); } Integer totalDocs = 0; Integer totalHL7 = 0; Hashtable<String, List<String>> typeDocLab = new Hashtable(); Enumeration keys = docType.keys(); while (keys.hasMoreElements()) { String keyDocLabId = ((String) keys.nextElement()); String valType = (String) docType.get(keyDocLabId); if (valType.equalsIgnoreCase("DOC")) { if (typeDocLab.containsKey("DOC")) { List<String> docids = typeDocLab.get("DOC"); docids.add(keyDocLabId);// add doc id to list typeDocLab.put("DOC", docids); } else { List<String> docids = new ArrayList<String>(); docids.add(keyDocLabId); typeDocLab.put("DOC", docids); } totalDocs++; } else if (valType.equalsIgnoreCase("HL7")) { if (typeDocLab.containsKey("HL7")) { List<String> hl7ids = typeDocLab.get("HL7"); hl7ids.add(keyDocLabId); typeDocLab.put("HL7", hl7ids); } else { List<String> hl7ids = new ArrayList<String>(); hl7ids.add(keyDocLabId); typeDocLab.put("HL7", hl7ids); } totalHL7++; } } Hashtable patientNumDoc = new Hashtable(); Enumeration patientIds = patientDocs.keys(); String patientIdStr = ""; Integer totalNumDocs = 0; while (patientIds.hasMoreElements()) { String key = (String) patientIds.nextElement(); patientIdStr += key; patientIdStr += ","; List<String> val = (List<String>) patientDocs.get(key); Integer numDoc = val.size(); patientNumDoc.put(key, numDoc); totalNumDocs += numDoc; } List<String> normals = ab_NormalDoc.get("normal"); List<String> abnormals = ab_NormalDoc.get("abnormal"); logger.debug("labdocs.size()=" + labdocs.size()); // set attributes request.setAttribute("pageNum", page); request.setAttribute("docType", docType); request.setAttribute("patientDocs", patientDocs); request.setAttribute("providerNo", providerNo); request.setAttribute("searchProviderNo", searchProviderNo); request.setAttribute("patientIdNames", patientIdNames); request.setAttribute("docStatus", docStatus); request.setAttribute("patientIdStr", patientIdStr); request.setAttribute("typeDocLab", typeDocLab); request.setAttribute("demographicNo", demographicNo); request.setAttribute("ackStatus", ackStatus); request.setAttribute("labdocs", labdocs); request.setAttribute("patientNumDoc", patientNumDoc); request.setAttribute("totalDocs", totalDocs); request.setAttribute("totalHL7", totalHL7); request.setAttribute("normals", normals); request.setAttribute("abnormals", abnormals); request.setAttribute("totalNumDocs", totalNumDocs); request.setAttribute("patientIdNamesStr", patientIdNamesStr); request.setAttribute("oldestLab", oldestLab != null ? DateUtils.formatDate(oldestLab, "yyyy-MM-dd HH:mm:ss") : null); return mapping.findForward("dms_page"); }
From source file:com.alfaariss.oa.profile.saml2.profile.sso.protocol.AuthenticationRequestProtocol.java
private AttributeStatement buildAttributeStatement(IAttributes attributes, String sAttributeNameFormat, Hashtable<String, String> htAttributeNameFormatMapper) { AttributeStatementBuilder attributeStatemenBuilder = (AttributeStatementBuilder) _builderFactory .getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME); AttributeStatement attributeStatement = attributeStatemenBuilder.buildObject(); AttributeBuilder attributeBuilder = (AttributeBuilder) _builderFactory .getBuilder(Attribute.DEFAULT_ELEMENT_NAME); Enumeration<?> enumNames = attributes.getNames(); while (enumNames.hasMoreElements()) { String sName = (String) enumNames.nextElement(); Attribute attribute = attributeBuilder.buildObject(); attribute.setName(sName);//from w w w . j a v a 2s .c o m //DD nameformat can be overwritten by a default or explicitly configured nameformat String sNameFormat = htAttributeNameFormatMapper.get(sName); if (sNameFormat == null) { if (sAttributeNameFormat != null && sAttributeNameFormat.trim().length() == 0) sNameFormat = null; else if (sAttributeNameFormat != null) sNameFormat = sAttributeNameFormat; else if (_bCompatible) sNameFormat = attributes.getFormat(sName); } if (sNameFormat != null) attribute.setNameFormat(sNameFormat); Object oValue = attributes.get(sName); if (oValue instanceof String) { XSStringBuilder stringBuilder = (XSStringBuilder) _builderFactory.getBuilder(XSString.TYPE_NAME); XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); stringValue.setValue((String) oValue); attribute.getAttributeValues().add(stringValue); } else if (oValue instanceof List) {//multivalue attribute XSStringBuilder stringBuilder = (XSStringBuilder) _builderFactory.getBuilder(XSString.TYPE_NAME); List listValues = (List) oValue; Iterator iterValues = listValues.iterator(); while (iterValues.hasNext()) { XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); stringValue.setValue((String) iterValues.next()); attribute.getAttributeValues().add(stringValue); } } else { StringBuffer sbDebug = new StringBuffer("Attribute '"); sbDebug.append(sName); sbDebug.append("' has an unsupported value; is not a String: "); sbDebug.append(oValue); _logger.debug(sbDebug.toString()); } attributeStatement.getAttributes().add(attribute); } return attributeStatement; }
From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.LoadRRFToDB.java
private static String[] createAndLoadTables(URI rrfLocation, boolean skipNonLexGridFiles, boolean recalcRootOnly, String dbServer, String dbDriver, String username, String password, LgMessageDirectorIF md, boolean validateMode) throws Exception { md.info("Connecting to RRF Files"); BufferedReader reader = getReader(rrfLocation.resolve("MRFILES.RRF")); md.info("Connecting to db Files"); Connection sqlConnection = DBUtility.connectToDatabase(dbServer, dbDriver, username, password); GenericSQLModifier gsm = new GenericSQLModifier(sqlConnection); Hashtable columnTypeMap = readMRCols(rrfLocation); Hashtable tableColumnMap = new Hashtable(); List tables = new ArrayList(); if (skipNonLexGridFiles) { // the only tables that I need to load tables.add("MRCONSO"); tables.add("MRDOC"); tables.add("MRREL"); tables.add("MRSAB"); tables.add("MRRANK"); if (!recalcRootOnly) { tables.add("MRDEF"); tables.add("MRSTY"); tables.add("MRSAT"); tables.add("MRHIER"); }//w w w. j a v a 2 s. c o m } md.info("Creating SQL database tables"); PreparedStatement create = null; PreparedStatement drop = null; String line = reader.readLine(); int mrhierHCDCol = -1; while (line != null) { String[] vals = stringToArray(line, '|'); // for MRFILES, all I care about is the following String file = vals[0]; String tableName = file.substring(0, file.indexOf('.')); // if file is MRHIER, remember HCD column number (base 0) if ("MRHIER".equalsIgnoreCase(tableName) && vals.length > 1) { mrhierHCDCol = Arrays.asList(vals[2].split(",")).indexOf("HCD"); } if (skipNonLexGridFiles || recalcRootOnly) { if (!tables.contains(tableName)) { line = reader.readLine(); continue; } } else { if (file.indexOf('/') != -1) { // skip files in subfolders. line = reader.readLine(); continue; } if (!tables.contains(tableName)) tables.add(tableName); } String[] columns = stringToArray(vals[2], ','); tableColumnMap.put(file, columns); StringBuffer tableCreateSQL = new StringBuffer(); tableCreateSQL.append("CREATE TABLE {IF NOT EXISTS} ^" + tableName + "^ ("); for (int i = 0; i < columns.length; i++) { tableCreateSQL.append(" ^" + columns[i] + "^ " + mapUMLSType((String) columnTypeMap.get(columns[i] + "|" + file)) + " default NULL,"); } // chop the last comma tableCreateSQL.deleteCharAt(tableCreateSQL.length() - 1); tableCreateSQL.append(") {TYPE}"); // make sure the table doesn't exist try { drop = sqlConnection.prepareStatement(gsm.modifySQL("DROP TABLE " + tableName + " {CASCADE}")); drop.executeUpdate(); drop.close(); } catch (SQLException e) { // most likely means that the table didn't exist. } create = sqlConnection.prepareStatement(gsm.modifySQL(tableCreateSQL.toString())); create.executeUpdate(); create.close(); line = reader.readLine(); } reader.close(); md.info("Creating indexes"); PreparedStatement createIndex = null; createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi1^ ON ^MRCONSO^ (^CUI^, ^SAB^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi2^ ON ^MRCONSO^ (^CUI^, ^AUI^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi3^ ON ^MRCONSO^ (^AUI^, ^CODE^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi4^ ON ^MRREL^ (^RELA^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi5^ ON ^MRREL^ (^REL^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi6^ ON ^MRREL^ (^RUI^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi7^ ON ^MRREL^ (^SAB^, ^RELA^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi8^ ON ^MRSAB^ (^RSAB^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi9^ ON ^MRRANK^ (^SAB^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi10^ ON ^MRRANK^ (^TTY^)")); createIndex.executeUpdate(); createIndex.close(); if (!recalcRootOnly) { createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi11^ ON ^MRDEF^ (^CUI^, ^SAB^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi12^ ON ^MRSAT^ (^METAUI^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi13^ ON ^MRSAT^ (^CUI^, ^SAB^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi14^ ON ^MRSAT^ (^CODE^, ^SAB^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi15^ ON ^MRSTY^ (^CUI^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection.prepareStatement( gsm.modifySQL("CREATE INDEX ^mi16^ ON ^MRHIER^ (^CUI^, ^AUI^, ^HCD^, ^SAB^, ^CXN^)")); createIndex.executeUpdate(); createIndex.close(); createIndex = sqlConnection .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi17^ ON ^MRHIER^ (^CUI^, ^SAB^, ^CXN^)")); createIndex.executeUpdate(); createIndex.close(); } PreparedStatement insert = null; Iterator allTables = tables.iterator(); Set rootCUIs = new HashSet(); while (allTables.hasNext()) { System.gc(); String table = (String) allTables.next(); md.info("Loading " + table); boolean loadingMrHier = table.equalsIgnoreCase("MRHIER"); StringBuffer insertSQL = new StringBuffer(); insertSQL.append("INSERT INTO " + table + " ("); String[] vals = (String[]) tableColumnMap.get(table + ".RRF"); for (int i = 0; i < vals.length; i++) { if (gsm.getDatabaseType().equals("ACCESS") && vals[i].equals("VALUE")) { // reserved word in MSAccess insertSQL.append("\"" + vals[i] + "\", "); } else { insertSQL.append(vals[i] + ", "); } } // chop the last comma and space insertSQL.deleteCharAt(insertSQL.length() - 2); insertSQL.append(") VALUES ("); for (int i = 0; i < vals.length; i++) { insertSQL.append("?, "); } // chop the last comma and space insertSQL.deleteCharAt(insertSQL.length() - 2); insertSQL.append(")"); insert = sqlConnection.prepareStatement(gsm.modifySQL(insertSQL.toString())); URI tableURI = rrfLocation.resolve(table + ".RRF"); if (verifyTableExists(tableURI)) { try { reader = getReader(tableURI); int count = 1; line = reader.readLine(); boolean restrictToRootCUIs = recalcRootOnly && table.equalsIgnoreCase("MRCONSO"); boolean restrictToRootRels = recalcRootOnly && table.equalsIgnoreCase("MRREL"); while (line != null && line.length() > 0) { // Note: If we are only using the data to recalculate // root nodes, // we only need CUIs defining root hierarchical terms // and any related // relationships. if (restrictToRootCUIs && !line.contains("|SRC|RHT|")) { line = reader.readLine(); continue; } String[] data = stringToArray(line, '|'); // If processing MRHIER, we only care about entries // relevant to // the specified MRHIER processing option. Many entries // in this file // we do not require since they can be derived from // MRREL. // MRHIER typically is much larger since it pre-computes // the entire // hierarchy, so we want to conserve time and space by // loading only // those entries that require special handling. if (loadingMrHier && mrhierHCDCol > 0 && data.length > mrhierHCDCol && StringUtils.isBlank(data[mrhierHCDCol])) { line = reader.readLine(); continue; } if (restrictToRootCUIs && data.length >= 1) rootCUIs.add(data[0]); if (restrictToRootRels && (data.length < 5 || (!rootCUIs.contains(data[0]) && !rootCUIs.contains(data[4])))) { line = reader.readLine(); continue; } for (int i = 0; i < vals.length; i++) { insert.setString(i + 1, data[i]); } insert.executeUpdate(); count++; line = reader.readLine(); if (validateMode && count > 100) { line = null; } if (count % 10000 == 0) { md.busy(); } if (count % 100000 == 0) { md.info("Loaded " + count + " into " + table); } } reader.close(); } catch (Exception e) { md.fatalAndThrowException("problem loading the table " + table, e); } } else { md.warn("Could not load table " + table + ". This" + "most likely means the corresponding RRF file" + "was not found in the source."); } insert.close(); System.gc(); } sqlConnection.close(); return (String[]) tables.toArray(new String[tables.size()]); }
From source file:com.alfaariss.oa.authentication.remote.aselect.RemoteASelectMethod.java
private UserEvent performLogout(HttpServletRequest request, HttpServletResponse response, ISession session, ASelectIDP oASelectIDP, String sASelectCredentials, ITGT tgt) throws OAException { Hashtable<String, String> htRequest = new Hashtable<String, String>(); try {//from ww w.j a v a 2 s . c o m StringBuffer sbMyURL = new StringBuffer(); sbMyURL.append(request.getRequestURL().toString()); sbMyURL.append("?").append(ISession.ID_NAME); sbMyURL.append("=").append(URLEncoder.encode(session.getId(), CHARSET)); htRequest.put(PARAM_LOCAL_AS_URL, sbMyURL.toString()); htRequest.put(PARAM_LOCAL_ORG, _sMyOrganization); htRequest.put(PARAM_ASELECTSERVER, oASelectIDP.getServerID()); htRequest.put(PARAM_ASELECTCREDENTIALS, sASelectCredentials); if (oASelectIDP.doSigning()) { String sSignature = createSignature(htRequest); htRequest.put(PARAM_SIGNATURE, sSignature); } htRequest.put(PARAM_REQUEST, SINGLE_LOGOUT);//not part of signature Hashtable<String, String> htResponse = null; try { htResponse = sendRequest(oASelectIDP.getURL(), htRequest); } catch (IOException e) { _logger.debug("Could not send single logout request to: " + oASelectIDP.getURL(), e); _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(), UserEvent.USER_LOGOUT_FAILED, this, "No logout response from: " + oASelectIDP.getID())); return UserEvent.USER_LOGOUT_FAILED; } String sResultCode = htResponse.get(PARAM_RESULTCODE); if (sResultCode == null) { StringBuffer sbError = new StringBuffer("Required parameter ("); sbError.append(PARAM_RESULTCODE); sbError.append(") not found in request=logout response ("); sbError.append(htResponse); sbError.append(") from A-Select Organization: "); sbError.append(oASelectIDP.getServerID()); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(), UserEvent.USER_LOGOUT_FAILED, this, "Invalid logout response")); return UserEvent.USER_LOGOUT_FAILED; } if (!ERROR_ASELECT_SUCCESS.equals(sResultCode)) { if (sResultCode.equals(ERROR_ASELECT_SERVER_UNKNOWN_TGT)) { _logger.debug("Credentials are unkown at the remote server, server returned result code: " + sResultCode); return logoutFinished(oASelectIDP, tgt, session, request); } StringBuffer sbError = new StringBuffer("Response parameter ("); sbError.append(PARAM_RESULTCODE); sbError.append(") from A-Select Organization '"); sbError.append(oASelectIDP.getServerID()); sbError.append("' contains error code: "); sbError.append(sResultCode); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(), UserEvent.USER_LOGOUT_FAILED, this, sResultCode)); return UserEvent.USER_LOGOUT_FAILED; } String sRemoteRid = htResponse.get(PARAM_RID); if (sRemoteRid == null) { StringBuffer sbError = new StringBuffer("Required parameter ("); sbError.append(PARAM_RID); sbError.append(") not found in request=logout response ("); sbError.append(htResponse); sbError.append(") from A-Select Organization: "); sbError.append(oASelectIDP.getServerID()); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(), UserEvent.USER_LOGOUT_FAILED, this, "Invalid logout response")); return UserEvent.USER_LOGOUT_FAILED; } String sRemoteUrl = htResponse.get(PARAM_AS_URL); if (sRemoteUrl == null) { StringBuffer sbError = new StringBuffer("Required parameter ("); sbError.append(PARAM_AS_URL); sbError.append(") not found in request=logout response ("); sbError.append(htResponse); sbError.append(") from A-Select Organization: "); sbError.append(oASelectIDP.getServerID()); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(), UserEvent.USER_LOGOUT_FAILED, this, "Invalid logout response")); return UserEvent.USER_LOGOUT_FAILED; } StringBuffer sbRedirect = new StringBuffer(sRemoteUrl); sbRedirect.append("&").append(PARAM_RID); sbRedirect.append("=").append(sRemoteRid); sbRedirect.append("&").append(PARAM_ASELECTSERVER); sbRedirect.append("=").append(oASelectIDP.getServerID()); _eventLogger.info(new UserEventLogItem(session, request.getRemoteAddr(), UserEvent.USER_LOGOUT_IN_PROGRESS, this, "Redirect user with request=logout")); session.persist(); _logger.debug("Redirecting user to: " + sbRedirect.toString()); try { response.sendRedirect(sbRedirect.toString()); } catch (IOException e) { _logger.debug("Could not send logout request to: " + sbRedirect.toString(), e); return UserEvent.USER_LOGOUT_FAILED; } } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error during logout initiation", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return UserEvent.USER_LOGOUT_IN_PROGRESS; }
From source file:com.alfaariss.oa.authentication.remote.aselect.RemoteASelectMethod.java
private UserEvent requestVerifyCredentials(HttpServletRequest oRequest, ISession oSession, ASelectIDP oASelectOrganization) throws OAException { UserEvent oUserEvent = UserEvent.AUTHN_METHOD_FAILED; Hashtable<String, String> htRequest = new Hashtable<String, String>(); try {// w w w. j a v a2 s .c om _logger.debug("Processing request: " + oRequest.getParameterMap().keySet()); String sASelectServerId = oRequest.getParameter(PARAM_ASELECTSERVER); if (sASelectServerId == null) { StringBuffer sbError = new StringBuffer("No '"); sbError.append(PARAM_ASELECTSERVER); sbError.append("' parameter found in request"); _logger.debug(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.REQUEST_INVALID, this, "Missing " + PARAM_ASELECTSERVER)); return UserEvent.REQUEST_INVALID; } if (!sASelectServerId.equals(oASelectOrganization.getServerID())) { StringBuffer sbError = new StringBuffer("Invalid '"); sbError.append(PARAM_ASELECTSERVER); sbError.append("' parameter found in request: "); sbError.append(sASelectServerId); _logger.debug(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.REQUEST_INVALID, this, "Invalid " + PARAM_ASELECTSERVER)); return UserEvent.REQUEST_INVALID; } String sRemoteRid = oRequest.getParameter(PARAM_RID); if (sRemoteRid == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_RID); sbError.append(") not found in request from A-Select Organization: "); sbError.append(sASelectServerId); _logger.debug(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.REQUEST_INVALID, this, "Missing " + PARAM_RID)); return UserEvent.REQUEST_INVALID; } String sASelectCredentials = oRequest.getParameter(PARAM_ASELECTCREDENTIALS); if (sASelectCredentials == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_ASELECTCREDENTIALS); sbError.append(") not found in request from A-Select Organization: "); sbError.append(sASelectServerId); _logger.debug(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.REQUEST_INVALID, this, "Missing " + PARAM_ASELECTCREDENTIALS)); return UserEvent.REQUEST_INVALID; } htRequest.put(PARAM_RID, sRemoteRid); htRequest.put(PARAM_ASELECTCREDENTIALS, sASelectCredentials); htRequest.put(PARAM_ASELECTSERVER, oASelectOrganization.getServerID()); htRequest.put(PARAM_LOCAL_ORG, _sMyOrganization); if (oASelectOrganization.doSigning()) { String sSignature = createSignature(htRequest); htRequest.put(PARAM_SIGNATURE, sSignature); } htRequest.put(PARAM_REQUEST, VERIFY_CREDENTIALS); Hashtable<String, String> htResponse = null; try { htResponse = sendRequest(oASelectOrganization.getURL(), htRequest); } catch (IOException e) { _logger.error("Could not verify credentials to: " + oASelectOrganization.getURL(), e); throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT); } _logger.debug("Processing response: " + htResponse); String sResultCode = htResponse.get(PARAM_RESULTCODE); if (sResultCode == null) { StringBuffer sbError = new StringBuffer("Required parameter ("); sbError.append(PARAM_RESULTCODE); sbError.append(") not found in request=verify_credentials response ("); sbError.append(htResponse); sbError.append(") from A-Select Organization: "); sbError.append(oASelectOrganization.getServerID()); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Invalid verify_credentials response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } if (!ERROR_ASELECT_SUCCESS.equals(sResultCode)) { //DD The result code form the remote server is not shown to the user if (ERROR_ASELECT_CANCEL.equals(sResultCode)) { _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.USER_CANCELLED, this, null)); oUserEvent = UserEvent.USER_CANCELLED; _logger.debug("User returned from organization where the cancel button was used"); oSession.getAttributes().remove(RemoteASelectMethod.class, _sMethodId + SESSION_SELECTED_ORGANIZATION); if (performReplay(oSession, oSession.getAttributes())) return UserEvent.AUTHN_METHOD_IN_PROGRESS; } else { _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.AUTHN_METHOD_FAILED, this, sResultCode)); oUserEvent = UserEvent.AUTHN_METHOD_FAILED; } } else { String sRemoteUID = htResponse.get(PARAM_UID); if (sRemoteUID == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_UID); sbError.append(") not found in response from A-Select Organization: "); sbError.append(sASelectServerId); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Invalid verify_credentials response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } //DD 2x URLDecode i.v.m. bug in A-Select 1.5 sRemoteUID = URLDecoder.decode(sRemoteUID, CHARSET); sRemoteUID = URLDecoder.decode(sRemoteUID, CHARSET); String sRemoteOrganization = htResponse.get(PARAM_ORGANIZATION); if (sRemoteOrganization == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_ORGANIZATION); sbError.append(") not found in response from A-Select Organization: "); sbError.append(oASelectOrganization.getID()); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Invalid verify_credentials response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } if (!sRemoteOrganization.equals(oASelectOrganization.getID())) { StringBuffer sbError = new StringBuffer("Unknown `"); sbError.append(PARAM_ORGANIZATION); sbError.append("` in response; Expected `"); sbError.append(oASelectOrganization.getID()); sbError.append("` received: "); sbError.append(sRemoteOrganization); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Unknown organization in response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } if (_idMapper != null) { sRemoteUID = _idMapper.remap(sRemoteUID); if (sRemoteUID == null) { _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.USER_UNKNOWN, this, null)); return UserEvent.USER_UNKNOWN; } } IUser oUser = oSession.getUser(); if (oUser == null) { if (_oRemoteASelectUserProvisioningProfile == null) { oUser = new ASelectRemoteUser(sRemoteOrganization, sRemoteUID, getID(), sASelectCredentials); } else { // Perform provisioning based on retrieved attributes CredentialResponseUserStorage oCRUS = new CredentialResponseUserStorage(htResponse); ProvisioningUser oProvisioningUser = _oRemoteASelectUserProvisioningProfile.getUser(oCRUS, sRemoteOrganization, sRemoteUID); oUser = new ASelectRemoteUser(oProvisioningUser, getID(), sASelectCredentials); } oSession.setUser(oUser); } String sRemoteAuthSP = htResponse.get(PARAM_AUTHSP); if (sRemoteAuthSP == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_AUTHSP); sbError.append(") not found in response from A-Select Organization: "); sbError.append(sASelectServerId); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Invalid verify_credentials response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } String sRemoteAuthSPLevel = htResponse.get(PARAM_AUTHSP_LEVEL); if (sRemoteAuthSPLevel == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_AUTHSP_LEVEL); sbError.append(") not found in response from A-Select Organization: "); sbError.append(sASelectServerId); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Invalid verify_credentials response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } String sRemoteAppLevel = htResponse.get(PARAM_APP_LEVEL); if (sRemoteAppLevel == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_APP_LEVEL); sbError.append(") not found in response from A-Select Organization: "); sbError.append(sASelectServerId); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Invalid verify_credentials response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } String sRemoteTGTExpTime = htResponse.get(PARAM_TGT_EXP_TIME); if (sRemoteTGTExpTime == null) { StringBuffer sbError = new StringBuffer("Request parameter ("); sbError.append(PARAM_TGT_EXP_TIME); sbError.append(") not found in response from A-Select Organization: "); sbError.append(sASelectServerId); _logger.warn(sbError.toString()); _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, "Invalid verify_credentials response")); throw new OAException(SystemErrors.ERROR_INTERNAL); } IAttributes oAttributes = new UserAttributes(); String sRemoteAttributes = htResponse.get(PARAM_ATTRIBUTES); if (sRemoteAttributes != null) { _logger.debug( "Remote A-Select Organization returned serialized attributes: " + sRemoteAttributes); IAttributes oRemoteAttributes = AttributeHelper.deserializeAttributes(sRemoteAttributes, CHARSET, oAttributes); oAttributes = mapAttributes(oRemoteAttributes, oUser.getAttributes()); } else oAttributes = oUser.getAttributes(); oUser.setAttributes(oAttributes); oUserEvent = UserEvent.AUTHN_METHOD_SUCCESSFUL; _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.AUTHN_METHOD_SUCCESSFUL, this, null)); } } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error during 'request=verify_credentials'", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return oUserEvent; }
From source file:com.netscape.cms.logging.LogFile.java
/** * Retrieve last "maxLine" number of system log with log lever >"level" * and from source "source". If the parameter is omitted. All entries * are sent back./*from www . j ava 2 s .c o m*/ */ public synchronized NameValuePairs retrieveLogContent(Hashtable<String, String> req) throws ServletException, IOException, EBaseException { NameValuePairs params = new NameValuePairs(); String tmp, fName = null; int maxLine = -1, level = -1; LogSource source = null; Vector<LogEntry> entries = null; if ((tmp = req.get(Constants.PR_LOG_ENTRY)) != null) { maxLine = Integer.parseInt(tmp); } if ((tmp = req.get(Constants.PR_LOG_LEVEL)) != null) { level = Integer.parseInt(tmp); } if ((tmp = req.get(Constants.PR_LOG_SOURCE)) != null) { source = LogSource.valueOf(Integer.parseInt(tmp)); } tmp = req.get(Constants.PR_LOG_NAME); if (!(tmp.equals(Constants.PR_CURRENT_LOG))) { fName = tmp; } else { flush(); } try { entries = readEntry(maxLine, level, source, fName); for (int i = 0; i < entries.size(); i++) { params.put(Integer.toString(i) + entries.elementAt(i).getEntry(), ""); } } catch (Exception e) { CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_WARN, "System log parse error"); } return params; }
From source file:org.fcrepo.server.access.FedoraAccessServlet.java
/** * <p>/*from ww w .j a v a2 s .com*/ * Process Fedora Access Request. Parse and validate the servlet input * parameters and then execute the specified request. * </p> * * @param request * The servlet request. * @param response * servlet The servlet response. * @throws ServletException * If an error occurs that effects the servlet's basic operation. * @throws IOException * If an error occurrs with an input or output operation. */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String PID = null; String sDefPID = null; String methodName = null; String dsID = null; Date asOfDateTime = null; Date versDateTime = null; Property[] userParms = null; boolean isGetObjectProfileRequest = false; boolean isGetDisseminationRequest = false; boolean isGetDatastreamDisseminationRequest = false; boolean xml = false; requestURI = request.getQueryString() != null ? request.getRequestURL().toString() + "?" + request.getQueryString() : request.getRequestURL().toString(); logger.info("Got request: {}", requestURI); // Parse servlet URL. // For the Fedora API-A-LITE "get" syntax, valid entries include: // // For dissemination requests: // http://host:port/fedora/get/pid/sDefPid/methodName // http://host:port/fedora/get/pid/sDefPid/methodName/timestamp // http://host:port/fedora/get/pid/sDefPid/methodName?parm=value[&parm=value] // http://host:port/fedora/get/pid/sDefPid/methodName/timestamp?parm=value[&parm=value] // // For object profile requests: // http://host:port/fedora/get/pid // http://host:port/fedora/get/pid/timestamp // // For datastream dissemination requests: // http://host:port/fedora/get/pid/dsID // http://host:port/fedora/get/pid/dsID/timestamp // // use substring to avoid an additional char array copy String[] URIArray = requestURI.substring(0, request.getRequestURL().length()).split("/"); if (URIArray.length == 6 || URIArray.length == 7) { // Request is either an ObjectProfile request or a datastream // request if (URIArray.length == 7) { // They either specified a date/time or a datastream id. if (URIArray[6].indexOf(":") == -1) { // If it doesn't contain a colon, they were after a // datastream, // so this is a DatastreamDissemination request dsID = URLDecoder.decode(URIArray[6], "UTF-8"); isGetDatastreamDisseminationRequest = true; } else { // If it DOES contain a colon, they were after a // date/time-stamped object profile try { versDateTime = DateUtility.parseDateStrict(URIArray[6]); } catch (ParseException e) { String message = "ObjectProfile Request Syntax Error: DateTime value " + "of \"" + URIArray[6] + "\" is not a valid DateTime format. " + " <br></br> The expected format for DateTime is \"" + "YYYY-MM-DDTHH:MM:SS.SSSZ\". " + " <br></br> The expected syntax for " + "ObjectProfile requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID[/dateTime] \" ." + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); /* * commented out for exception.jsp test * response.setStatus * (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); * response * .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR * , message); return; commented out for exception.jsp * test */ } asOfDateTime = versDateTime; isGetObjectProfileRequest = true; } } else { // URIArray.length==6 so this is a GetObjectProfile request isGetObjectProfileRequest = true; } } else if (URIArray.length > 7) { // Request is either dissemination request or timestamped get // datastream request methodName = URLDecoder.decode(URIArray[7], "UTF-8"); if (URIArray.length == 8) { if (URIArray[6].indexOf(":") == -1) { // If it doesn't contain a colon, they were after a // timestamped // datastream, so this is a GetDatastreamDissemination // request. dsID = URLDecoder.decode(URIArray[6], "UTF-8"); try { versDateTime = DateUtility.parseDateStrict(URIArray[7]); } catch (ParseException e) { String message = "GetDatastreamDissemination Request Syntax Error: DateTime value " + "of \"" + URIArray[7] + "\" is not a valid DateTime format. " + " <br></br> The expected format for DateTime is \"" + "YYYY-MM-DDTHH:MM:SS.SSSZ\". " + " <br></br> The expected syntax for GetDatastreamDissemination requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID/dsID[/dateTime] \" " + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); } asOfDateTime = versDateTime; isGetDatastreamDisseminationRequest = true; } else { isGetDisseminationRequest = true; } } else if (URIArray.length == 9) { try { versDateTime = DateUtility.parseDateStrict(URIArray[8]); } catch (ParseException e) { String message = "Dissemination Request Syntax Error: DateTime value " + "of \"" + URIArray[8] + "\" is not a valid DateTime format. " + " <br></br> The expected format for DateTime is \"" + "YYYY-MM-DDTHH:MM:SS.SSS\". " + " <br></br> The expected syntax for Dissemination requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID/sDefPID/methodName[/dateTime][?ParmArray] \" " + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); /* * commented out for exception.jsp test * response.setStatus(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR); * response.sendError(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR, message); return; commented * out for exception.jsp test */ } asOfDateTime = versDateTime; isGetDisseminationRequest = true; } if (URIArray.length > 9) { String message = "Dissemination Request Syntax Error: The expected " + "syntax for Dissemination requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID/sDefPID/methodName[/dateTime][?ParmArray] \" " + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); /* * commented out for exception.jsp test * response.setStatus(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR); * response.sendError(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR, message); return; commented out * for exception.jsp test */ } } else { // Bad syntax; redirect to syntax documentation page. response.sendRedirect("/userdocs/client/browser/apialite/index.html"); return; } // Separate out servlet parameters from method parameters Hashtable<String, String> h_userParms = new Hashtable<String, String>(); for (Enumeration<?> e = request.getParameterNames(); e.hasMoreElements();) { String name = URLDecoder.decode((String) e.nextElement(), "UTF-8"); if (isGetObjectProfileRequest && name.equalsIgnoreCase("xml")) { xml = Boolean.parseBoolean(request.getParameter(name)); } else { String value = URLDecoder.decode(request.getParameter(name), "UTF-8"); h_userParms.put(name, value); } } // API-A interface requires user-supplied parameters to be of type // Property[] so create Property[] from hashtable of user parameters. int userParmCounter = 0; userParms = new Property[h_userParms.size()]; for (Enumeration<String> e = h_userParms.keys(); e.hasMoreElements();) { Property userParm = new Property(); userParm.name = e.nextElement(); userParm.value = h_userParms.get(userParm.name); userParms[userParmCounter] = userParm; userParmCounter++; } PID = URIArray[5]; String actionLabel = "Access"; try { if (isGetObjectProfileRequest) { logger.debug("Servicing getObjectProfile request (PID={}, asOfDate={})", PID, versDateTime); Context context = ReadOnlyContext.getContext(HTTP_REQUEST.REST.uri, request); getObjectProfile(context, PID, asOfDateTime, xml, request, response); logger.debug("Finished servicing getObjectProfile request"); } else if (isGetDisseminationRequest) { sDefPID = URIArray[6]; logger.debug("Servicing getDissemination request (PID={}, sDefPID={}, methodName={}, asOfDate={})", PID, sDefPID, methodName, versDateTime); Context context = ReadOnlyContext.getContext(HTTP_REQUEST.REST.uri, request); getDissemination(context, PID, sDefPID, methodName, userParms, asOfDateTime, response, request); logger.debug("Finished servicing getDissemination request"); } else if (isGetDatastreamDisseminationRequest) { logger.debug("Servicing getDatastreamDissemination request " + "(PID={}, dsID={}, asOfDate={})", PID, dsID, versDateTime); Context context = ReadOnlyContext.getContext(HTTP_REQUEST.REST.uri, request); getDatastreamDissemination(context, PID, dsID, asOfDateTime, response, request); logger.debug("Finished servicing getDatastreamDissemination " + "request"); } } catch (MethodNotFoundException e) { logger.error("Method not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (DatastreamNotFoundException e) { logger.error("Datastream not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (ObjectNotFoundException e) { logger.error("Object not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (DisseminationException e) { logger.error("Dissemination failed: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (ObjectNotInLowlevelStorageException e) { logger.error("Object or datastream not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (AuthzException ae) { logger.error("Authorization failed for request: " + requestURI + " (actionLabel=" + actionLabel + ")", ae); throw RootException.getServletException(ae, request, actionLabel, EMPTY_STRING_ARRAY); } catch (Throwable th) { logger.error("Unexpected error servicing API-A request", th); throw new InternalError500Exception("", th, request, actionLabel, "", EMPTY_STRING_ARRAY); } }
From source file:com.netscape.admin.certsrv.Console.java
/** * New authentication method, via CGI. Authenticate the user through the admin server CGI. */* ww w .j a v a 2 s . c om*/ * @param adminServerURL url of the admin server * @param info console info * @param user user dn * @param pw user password * @return true if successful. false otherwise. */ private synchronized final boolean authenticate_user(String adminServerURL, ConsoleInfo info, String user, String pw) { URL url; try { // DT 5/14/98 This method of URL construction provides some limited // validation of the URL, and eliminates any preexisting uri component. url = new URL(new URL(adminServerURL), "/admin-serv/authenticate"); } catch (MalformedURLException mue) { Debug.println("Console:authenticate_user():Unable to create authentication URL"); return false; } Hashtable<String, String> ht = new Hashtable<>(); boolean successfulAuth = invoke_task(url, user, pw, ht); String param; // DT 6/29/98 Check Password Expiration data if ((param = ht.get("NW_PASSWD_EXPIRING")) != null) { int secondsToExpiration = Integer.parseInt(param); if (secondsToExpiration == 0) { // Password expired. For now, show error and exit. // Later, this should jump to a UI. String msg = _resource.getString("error", "pwExpired"); System.err.println(msg); JOptionPane.showMessageDialog(com.netscape.management.client.console.SplashScreen.getInstance(), msg, _resource.getString("error", "pwTitle"), JOptionPane.ERROR_MESSAGE); ModalDialogUtil.sleep(); System.exit(1); } else { double days = (secondsToExpiration / (1.0 * 3600 * 24)); String msg = MessageFormat.format(_resource.getString("warning", "pwExpireSoon"), new Object[] { new Double(days) }); Debug.println("Console: " + msg); JOptionPane.showMessageDialog(com.netscape.management.client.console.SplashScreen.getInstance(), msg, _resource.getString("warning", "title"), JOptionPane.ERROR_MESSAGE); ModalDialogUtil.sleep(); } } if (!successfulAuth) return false; if ((param = ht.get("UserDN")) != null) info.setAuthenticationDN(param); else { Debug.println("Console:authenticate_user():UserDN not found"); info.setAuthenticationDN(user); } info.setAuthenticationPassword(pw); info.setAuthenticationValues(ht); return true; }
From source file:hd.controller.AddImageToProjectServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a v a 2s .c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } //Init Jpa CategoryJpaController categoryJpa = new CategoryJpaController(emf); StyleJpaController styleJpa = new StyleJpaController(emf); ProjectJpaController projectJpa = new ProjectJpaController(emf); IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf); // get Object Category by categoryId int cateId = Integer.parseInt((String) params.get("ddlCategory")); Category cate = categoryJpa.findCategory(cateId); // get Object Style by styleId int styleId = Integer.parseInt((String) params.get("ddlStyle")); Style style = styleJpa.findStyle(styleId); // get Object Project by projectId int projectId = Integer.parseInt((String) params.get("txtProjectId")); Project project = projectJpa.findProject(projectId); project.setStatus(Constant.STATUS_WAIT); projectJpa.edit(project); //Get param String title = (String) params.get("title"); String description = (String) params.get("description"); String url = "images/" + fileName; //Init IdeabookPhoto IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project); photoJpa.create(photo); url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId; //System HDSystem system = new HDSystem(); system.setNotificationProject(request); response.sendRedirect(url); } } catch (Exception e) { log("Error at AddImageToProjectServlet: " + e.getMessage()); } finally { out.close(); } }