List of usage examples for java.lang StringBuffer substring
@Override public synchronized String substring(int start, int end)
From source file:cx.fbn.nevernote.sql.NoteTable.java
public Note mapNoteFromQuery(NSqlQuery query, boolean loadContent, boolean loadResources, boolean loadRecognition, boolean loadBinary, boolean loadTags) { DateFormat indfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); // indfm = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy"); Note n = new Note(); NoteAttributes na = new NoteAttributes(); n.setAttributes(na);/*w w w .jav a 2s . co m*/ n.setGuid(query.valueString(0)); n.setUpdateSequenceNum(new Integer(query.valueString(1))); n.setTitle(query.valueString(2)); try { n.setCreated(indfm.parse(query.valueString(3)).getTime()); n.setUpdated(indfm.parse(query.valueString(4)).getTime()); n.setDeleted(indfm.parse(query.valueString(5)).getTime()); } catch (ParseException e) { e.printStackTrace(); } n.setActive(query.valueBoolean(6, true)); n.setNotebookGuid(query.valueString(7)); try { String attributeSubjectDate = query.valueString(8); if (!attributeSubjectDate.equals("")) na.setSubjectDate(indfm.parse(attributeSubjectDate).getTime()); } catch (ParseException e) { e.printStackTrace(); } na.setLatitude(new Float(query.valueString(9))); na.setLongitude(new Float(query.valueString(10))); na.setAltitude(new Float(query.valueString(11))); na.setAuthor(query.valueString(12)); na.setSource(query.valueString(13)); na.setSourceURL(query.valueString(14)); na.setSourceApplication(query.valueString(15)); na.setContentClass(query.valueString(16)); if (loadTags) { List<String> tagGuids = noteTagsTable.getNoteTags(n.getGuid()); List<String> tagNames = new ArrayList<String>(); TagTable tagTable = db.getTagTable(); for (int i = 0; i < tagGuids.size(); i++) { String currentGuid = tagGuids.get(i); Tag tag = tagTable.getTag(currentGuid); if (tag.getName() != null) tagNames.add(tag.getName()); else tagNames.add(""); } n.setTagNames(tagNames); n.setTagGuids(tagGuids); } if (loadContent) { QTextCodec codec = QTextCodec.codecForLocale(); codec = QTextCodec.codecForName("UTF-8"); String unicode = codec.fromUnicode(query.valueString(17)).toString(); // This is a hack. Basically I need to convert HTML Entities to "normal" text, but if I // convert the < character to < it will mess up the XML parsing. So, to get around this // I am "bit stuffing" the < to &< so StringEscapeUtils doesn't unescape it. After // I'm done I convert it back. StringBuffer buffer = new StringBuffer(unicode); if (Global.enableHTMLEntitiesFix && unicode.indexOf("&#") > 0) { unicode = query.valueString(17); //System.out.println(unicode); //unicode = unicode.replace("<", "&_lt;"); //unicode = codec.fromUnicode(StringEscapeUtils.unescapeHtml(unicode)).toString(); //unicode = unicode.replace("&_lt;", "<"); //System.out.println("************************"); int j = 1; for (int i = buffer.indexOf("&#"); i != -1 && buffer.indexOf("&#", i) > 0; i = buffer.indexOf("&#", i + 1)) { j = buffer.indexOf(";", i) + 1; if (i < j) { String entity = buffer.substring(i, j).toString(); int len = entity.length() - 1; String tempEntity = entity.substring(2, len); try { Integer.parseInt(tempEntity); entity = codec.fromUnicode(StringEscapeUtils.unescapeHtml4(entity)).toString(); buffer.delete(i, j); buffer.insert(i, entity); } catch (Exception e) { } } } } n.setContent(unicode); // n.setContent(query.valueString(16).toString()); String contentHash = query.valueString(18); if (contentHash != null) n.setContentHash(contentHash.getBytes()); n.setContentLength(new Integer(query.valueString(19))); } if (loadResources) n.setResources(noteResourceTable.getNoteResources(n.getGuid(), loadBinary)); if (loadRecognition) { if (n.getResources() == null) { List<Resource> resources = noteResourceTable.getNoteResourcesRecognition(n.getGuid()); n.setResources(resources); } else { // We need to merge the recognition resources with the note resources retrieved earlier for (int i = 0; i < n.getResources().size(); i++) { Resource r = noteResourceTable.getNoteResourceRecognition(n.getResources().get(i).getGuid()); n.getResources().get(i).setRecognition(r.getRecognition()); } } } n.setContent(fixCarriageReturn(n.getContent())); return n; }
From source file:com.topsec.tsm.sim.report.web.TopoReportController.java
public String reportQuery(SID sid, HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject json = new JSONObject(); ReportBean bean = new ReportBean(); bean = ReportUiUtil.tidyFormBean(bean, request); String[] talCategory = bean.getTalCategory(); ReportModel.setBeanPropery(bean);/*from w w w .ja v a 2 s . c o m*/ RptMasterTbService rptMasterTbImp = (RptMasterTbService) SpringContextServlet.springCtx .getBean(ReportUiConfig.MstBean); List<Map> subResult = new ArrayList<Map>(); Map<Integer, Integer> rowColumns = new HashMap<Integer, Integer>(); List<Map<String, Object>> subResultTemp = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql, new Object[] { StringUtil.toInt(bean.getMstrptid(), StringUtil.toInt(bean.getTalTop(), 5)) }); Map<Integer, Integer> rowColumnsTeMap = ReportModel.getRowColumns(subResultTemp); int evtRptsize = subResultTemp.size(); if (!GlobalUtil.isNullOrEmpty(subResultTemp)) { subResult.addAll(subResultTemp); rowColumns.putAll(rowColumnsTeMap); } String nodeType = bean.getNodeType(); String dvcaddress = bean.getDvcaddress(); if (!GlobalUtil.isNullOrEmpty(bean.getDvctype()) && bean.getDvctype().startsWith("Profession/Group") && !GlobalUtil.isNullOrEmpty(nodeType) && !GlobalUtil.isNullOrEmpty(dvcaddress)) { Map map = TopoUtil.getAssetEvtMstMap(); String mstIds = null; List<SimDatasource> simDatasources = dataSourceService.getByIp(dvcaddress); if (!GlobalUtil.isNullOrEmpty(simDatasources)) { mstIds = ""; for (SimDatasource simDatasource : simDatasources) { if (map.containsKey(simDatasource.getSecurityObjectType())) { mstIds += map.get(simDatasource.getSecurityObjectType()).toString() + ":::"; } else { String keyString = getStartStringKey(map, simDatasource.getSecurityObjectType()); if (!GlobalUtil.isNullOrEmpty(keyString)) { mstIds += map.get(keyString).toString() + ":::"; } } } if (mstIds.length() > 3) { mstIds = mstIds.substring(0, mstIds.length() - 3); } } else { if (map.containsKey(nodeType)) { mstIds = map.get(nodeType).toString(); } else { String keyString = getStartStringKey(map, nodeType); if (!GlobalUtil.isNullOrEmpty(keyString)) { mstIds = map.get(keyString).toString(); } } } /**/ if (!GlobalUtil.isNullOrEmpty(mstIds)) { String[] mstIdArr = mstIds.split(":::"); for (String string : mstIdArr) { List<Map<String, Object>> subTemp = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql, new Object[] { StringUtil.toInt(string, StringUtil.toInt(bean.getTalTop(), 5)) }); if (!GlobalUtil.isNullOrEmpty(subTemp)) { int maxCol = 0; if (!GlobalUtil.isNullOrEmpty(rowColumns)) { maxCol = getMaxOrMinKey(rowColumns, 1); } for (Map map2 : subTemp) { Integer row = (Integer) map2.get("subRow") + maxCol; map2.put("subRow", row); } subResult.addAll(subTemp); Map<Integer, Integer> rowColTemp = ReportModel.getRowColumns(subTemp); rowColumns.putAll(rowColTemp); // rowColumns=newLocationMap(rowColumns, rowColTemp); } } } } StringBuffer layout = new StringBuffer(); Map<String, Object> params = new HashMap<String, Object>(); params.put("dvcType", bean.getDvctype()); params.put("talTop", bean.getTalTop()); params.put("mstId", bean.getMstrptid()); params.put("eTime", bean.getTalEndTime()); params.put("rootId", bean.getRootId()); params.put("assGroupNodeId", bean.getAssGroupNodeId()); params.put("topoId", bean.getTopoId()); params.put("nodeLevel", bean.getNodeLevel()); params.put("nodeType", bean.getNodeType()); String sUrl = null; int screenWidth = StringUtil.toInt(request.getParameter("screenWidth"), 1280) - 25 - 200; StringBuffer subUrl = new StringBuffer(); Map layoutValue = new HashMap(); for (int i = 0, len = subResult.size(); i < len; i++) { params.remove("sTime"); Map subMap = subResult.get(i); if (i == 0) { bean.setViewItem(StringUtil.toString(subMap.get("viewItem"), "")); } Integer row = (Integer) subMap.get("subRow"); layout.append(row + ":" + subMap.get("subColumn") + ","); if (GlobalUtil.isNullOrEmpty(subMap)) { continue; } params.put("sTime", bean.getTalStartTime()); if (i < evtRptsize) { sUrl = getUrl(ReportUiConfig.subEvtUrl, request, params, bean.getTalCategory(), true).toString(); } else { sUrl = getUrl(ReportUiConfig.subEvtUrl, request, params, bean.getTalCategory(), false).toString(); } subUrl.replace(0, subUrl.length(), sUrl); subUrl.append("&").append(ReportUiConfig.subrptid).append("=").append(subMap.get("subId")); subUrl.substring(0, subUrl.length()); int column = rowColumns.get(row); String width = String.valueOf((screenWidth - 10 * column) / column); String _column = subMap.get("subColumn").toString(); layoutValue.put(row + _column, ReportUiUtil.createSubTitle(subMap, width, subUrl.toString(), bean.getTalCategory(), StringUtil.toInt(bean.getTalTop(), 5))); } if (!GlobalUtil.isNullOrEmpty(subResult) && subResult.size() > 0) { if (!GlobalUtil.isNullOrEmpty(subResult.get(0).get("mstName"))) { request.setAttribute("title", subResult.get(0).get("mstName")); } } String htmlLayout = ReportModel.createMstTable(layout.toString(), layoutValue); StringBuffer sb = getExportUrl(request, params, talCategory, true); request.setAttribute("expUrl", sb.toString()); request.setAttribute("layout", htmlLayout); request.setAttribute("bean", bean); return "/page/report/assetStatusEvtReport"; }
From source file:org.opentides.service.impl.NotificationServiceImpl.java
@Scheduled(fixedDelayString = "${notification.delay}") @Transactional/* w ww.j ava 2 s . c o m*/ public void executeNotification() { int max = StringUtil.convertToInt(limit, 20); for (int i = 0; i < max; i++) { List<Notification> notifications = notificationDao.findNewNotifications(1); if (notifications == null || notifications.isEmpty()) break; Notification n = notifications.get(0); Status status = null; boolean processed = false; StringBuffer remarks = new StringBuffer(); try { if ("EMAIL".equals(n.getMedium())) { n.setStatus(Status.IN_PROCESS.toString()); notificationDao.saveEntityModel(n); // send email if (n.getSubject() == null) n.setSubject(""); if (StringUtil.isEmpty(n.getAttachment())) { emailHandler.sendEmail(n.getRecipientReference().split(","), new String[] { n.getEmailCC() }, new String[] {}, n.getEmailReplyTo(), n.getSubject(), n.getMessage()); } else { // send with attachment File attachment = new File(n.getAttachment()); emailHandler.sendEmail(n.getRecipientReference().split(","), new String[] { n.getEmailCC() }, new String[] {}, n.getEmailReplyTo(), n.getSubject(), n.getMessage(), new File[] { attachment }); } status = Status.PROCESSED; processed = true; remarks.append("Email successfully sent to " + n.getRecipientReference() + ".\n"); } if ("SMS".equals(n.getMedium())) { n.setStatus(Status.IN_PROCESS.toString()); notificationDao.saveEntityModel(n); // send SMS // processed = smsService.send(n.getRecipientReference(), n.getMessage()); // if(processed) { // status = Status.PROCESSED; // remarks.append("SMS sent to " + n.getRecipientReference() + "\n"); // } else { // status = Status.FAILED; // } } if (processed) { if (status != null) n.setStatus(status.toString()); n.setRemarks(remarks.toString()); notificationDao.saveEntityModel(n); } } catch (Exception e) { _log.error("Error encountered while sending notification", e); remarks.append(e.getMessage()); if (remarks.length() > 3999) n.setRemarks(remarks.substring(0, 3999)); else n.setRemarks(remarks.toString() + "\n"); n.setStatus(Status.FAILED.toString()); notificationDao.saveEntityModel(n); } } }
From source file:org.codehaus.mojo.sql.SqlExecMojo.java
/** * read in lines and execute them/*ww w . j a v a 2 s . c om*/ * * @param reader the reader * @param out the outputstream * @throws SQLException * @throws IOException */ private void runStatements(Reader reader, PrintStream out) throws SQLException, IOException { String line; if (enableBlockMode) { //no need to parse the content, ship it directly to jdbc in one sql statement line = IOUtil.toString(reader); execSQL(line, out); return; } StringBuffer sql = new StringBuffer(); BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { if (!keepFormat) { line = line.trim(); } if (!keepFormat) { if (line.startsWith("//")) { continue; } if (line.startsWith("--")) { continue; } StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { String token = st.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } } if (!keepFormat) { sql.append(" ").append(line); } else { sql.append("\n").append(line); } // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (!keepFormat) { if (SqlSplitter.containsSqlEnd(line, delimiter) == SqlSplitter.NO_END) { sql.append("\n"); } } if ((delimiterType.equals(DelimiterType.NORMAL) && SqlSplitter.containsSqlEnd(line, delimiter) > 0) || (delimiterType.equals(DelimiterType.ROW) && line.trim().equals(delimiter))) { execSQL(sql.substring(0, sql.length() - delimiter.length()), out); sql.setLength(0); // clean buffer } } // Catch any statements not followed by ; if (!sql.toString().equals("")) { execSQL(sql.toString(), out); } }
From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java
public String replaceSystemValues(String string, Map beans) { StringBuffer buffer = new StringBuffer(string); Set beanNames = beans.keySet(); for (Iterator it = beanNames.iterator(); it.hasNext();) { String beanName = (String) it.next(); // see if the string contains reference(s) to the supported beans for (int i = buffer.indexOf(beanName), j = beanName.length(); i != -1; i = buffer.indexOf(beanName)) { // if it does, parse the property of the bean the report query references int k = buffer.indexOf("}", i + j); if (k == -1) throw new RuntimeException("Missing closing brace \"}\" in report query: " + string); String property = buffer.substring(i + j, k); // construct the bean property's corresponding "getter" method String getter = null; String param = null;// ww w . j ava 2 s . co m if (beanName.indexOf(".attribute.") != -1) { getter = "getAttribute"; param = property; } else if (beanName.indexOf(".property.") != -1) { getter = "getProperties"; param = null; } else { getter = "get" + Character.toUpperCase(property.charAt(0)) + property.substring(1); param = null; } try { // use reflection to invoke the method on the bean Object bean = beans.get(beanName); Class clasz = bean.getClass(); Class[] args = param == null ? (Class[]) null : new Class[] { String.class }; Method method = clasz.getMethod(getter, args); Object result = method.invoke(bean, (param == null ? (Object[]) null : new Object[] { param })); if (beanName.indexOf(".property.") != -1) { clasz = org.sakaiproject.entity.api.ResourceProperties.class; getter = "getProperty"; args = new Class[] { String.class }; param = property; method = clasz.getMethod(getter, args); result = method.invoke(result, new Object[] { param }); } // replace the bean expression in the report query with the actual value of calling the bean's corresponding getter method buffer.delete(i, k + 1); buffer.insert(i, (result == null ? "null" : result instanceof Time ? ((Time) result).toStringSql() : result.toString().replaceAll("'", "''"))); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(), ex); } } } return buffer.toString(); }
From source file:com.codegarden.nativenavigation.JuceActivity.java
public static final HTTPStream createHTTPStream(String address, boolean isPost, byte[] postData, String headers, int timeOutMs, int[] statusCode, StringBuffer responseHeaders, int numRedirectsToFollow, String httpRequestCmd) {// w w w . jav a 2 s .c o m // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL) if (timeOutMs < 0) timeOutMs = 0; else if (timeOutMs == 0) timeOutMs = 30000; // headers - if not empty, this string is appended onto the headers that are used for the request. It must therefore be a valid set of HTML header directives, separated by newlines. // So convert headers string to an array, with an element for each line String headerLines[] = headers.split("\\n"); for (;;) { try { HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection()); if (connection != null) { try { connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(timeOutMs); connection.setReadTimeout(timeOutMs); // Set request headers for (int i = 0; i < headerLines.length; ++i) { int pos = headerLines[i].indexOf(":"); if (pos > 0 && pos < headerLines[i].length()) { String field = headerLines[i].substring(0, pos); String value = headerLines[i].substring(pos + 1); if (value.length() > 0) connection.setRequestProperty(field, value); } } connection.setRequestMethod(httpRequestCmd); if (isPost) { connection.setDoOutput(true); if (postData != null) { OutputStream out = connection.getOutputStream(); out.write(postData); out.flush(); } } HTTPStream httpStream = new HTTPStream(connection, statusCode, responseHeaders); // Process redirect & continue as necessary int status = statusCode[0]; if (--numRedirectsToFollow >= 0 && (status == 301 || status == 302 || status == 303 || status == 307)) { // Assumes only one occurrence of "Location" int pos1 = responseHeaders.indexOf("Location:") + 10; int pos2 = responseHeaders.indexOf("\n", pos1); if (pos2 > pos1) { String newLocation = responseHeaders.substring(pos1, pos2); // Handle newLocation whether it's absolute or relative URL baseUrl = new URL(address); URL newUrl = new URL(baseUrl, newLocation); String transformedNewLocation = newUrl.toString(); if (transformedNewLocation != address) { address = transformedNewLocation; // Clear responseHeaders before next iteration responseHeaders.delete(0, responseHeaders.length()); continue; } } } return httpStream; } catch (Throwable e) { connection.disconnect(); } } } catch (Throwable e) { } return null; } }
From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.UMLSBaseCode.java
/** * Adds qualification to concepts and associations in the LexGrid * repository.//from w w w . j a va 2 s .com * * @param aq * Qualification information from the UMLS source. * @param constructHCD * Indicates whether artificial context values should be * constructed if not provided in the UMLS information. * @param rela * The relationship attribute defined by UMLS (can be empty or * null). * @param totalCount * The total number of context links qualified previously. * @return The number of contextual links qualified in the repository for * the given UMLS info. * @throws SQLException */ protected int loadContext(AssociationQualification aq, boolean constructHCD, String rela, int totalCount) throws SQLException { // If a context identifier was assigned, use it. // If a context identifier is not assigned and the option to construct // is enabled, // derive one based on the root concept code and path to root AUI // values. int contextLinks = 0; String hcd = aq.qualifierValue; if (constructHCD && StringUtils.isBlank(hcd) && StringUtils.isNotBlank(aq.pathToRoot) && StringUtils.isNotBlank(aq.sourceConceptCode)) { MessageDigest md = getSHA1(); md.reset(); md.update(aq.pathToRoot.getBytes()); hcd = String.valueOf(md.digest(aq.sourceConceptCode.getBytes())); } if (StringUtils.isBlank(hcd)) return 0; // Iterate through the path to root and determine the codes for // participating AUIs. We maintain a LRU cache of AUIs to codes to // assist. // If the associated code is not in the cache, find and cache it here. ListOrderedMap orderedPtrAUIToCode = new ListOrderedMap(); // Break up the path to root into AUIs ... String[] auis = aq.pathToRoot.split("\\."); if (auis.length > 0) { // Check the cache for each. If not found, perform and cache the // AUI to code mapping. PreparedStatement getPTRCode = umlsConnection2_ .prepareStatement("SELECT CODE FROM MRCONSO WHERE AUI = ?"); try { String nextCode, nextAUI; for (int i = 0; i < auis.length; i++) { // Check for registered code in the cache. nextAUI = auis[i]; nextCode = (String) auiToCodeCache_.get(nextAUI); // If not cached, perform lookup ... if (nextCode == null) { getPTRCode.setString(1, nextAUI); ResultSet ptrCodes = getPTRCode.executeQuery(); int count = 0; try { while (ptrCodes.next()) { count++; nextCode = ptrCodes.getString(1); } } finally { ptrCodes.close(); } // If one to one mapping (probably should always be, but // doesn't // hurt to check), add to the cache for quick lookup // later... if (count == 1) auiToCodeCache_.put(nextAUI, nextCode); } // Was it resolved? if (nextCode != null) orderedPtrAUIToCode.put(nextAUI, nextCode); } } finally { getPTRCode.close(); } } // Ensure we have included the original AUI to code mapping from the // provided UMLS qualification info; inserted last as the root // of the path. orderedPtrAUIToCode.put(aq.sourceConceptAUI, aq.sourceConceptCode); // ///////////////////////////////////////////////////////////////////// // We have all the participating codes and AUIs. // Add context qualifiers to the text presentation of each concept // based on code/AUI pairs. // ///////////////////////////////////////////////////////////////////// for (OrderedMapIterator omi = orderedPtrAUIToCode.orderedMapIterator(); omi.hasNext();) { omi.next(); String aui = (String) omi.getKey(); String code = (String) omi.getValue(); if (code != null) qualifyConceptPresentation(code, aui, aq.codingSchemeName, aq.qualifierName, hcd); } // ///////////////////////////////////////////////////////////////////// // At this point we have taken care of all the concept qualifiers. // Now find and similarly tag each participating association link // between AUIs in the path to root chain. // ///////////////////////////////////////////////////////////////////// // Statements to find LexGrid association to concept mappings. // Check source to target (parent association as processed) // or target to source (child association as processed). // Honor the association specified in the MRHIER entry, if provided. // For example, the UMLS 'inverse_isa' is mapped on load to 'hasSubtype' // association name; account for that here. String assoc = mapRela(rela); // If a specific relation attribute (rela) was not provided, consider // all relevant // hierarchical associations (including UMLS standard or source-specific // names). String assocParam = StringUtils.isNotBlank(assoc) ? '\'' + assoc + '\'' : toCommaDelimitedWithQuotes(getHierAssocNames(aq.codingSchemeName)); // Create statements to navigate both directions (up & down the // contextual chain). PreparedStatement getRelationship_1 = sqlConnection_.prepareStatement(new StringBuffer( "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", " + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" WHERE " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ? AND") .append(" " + stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId + " IN (") .append(assocParam).append(")").toString()); PreparedStatement getRelationship_2 = sqlConnection_.prepareStatement(new StringBuffer( "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", " + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" WHERE " + stc_.targetEntityCodeOrId + " = ? AND " + stc_.sourceEntityCodeOrId + " = ? AND") .append(" " + stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId + " IN (") .append(assocParam).append(")").toString()); // Statement to update a multi-attributes key for an association // mapping. PreparedStatement updateMAK = sqlConnection_.prepareStatement(new StringBuffer("UPDATE ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" SET " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + " = ? " + " WHERE " + stc_.codingSchemeNameOrId + " = ?") .append(" AND " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ?") .append(" AND " + stc_.entityCodeOrAssociationId + " = ?").toString()); // Locate and qualify each affected association link with the context ID // ... try { PreparedStatement[] stmts = new PreparedStatement[] { getRelationship_1, getRelationship_2 }; for (int s = 0; s < stmts.length; s++) { PreparedStatement stmt = stmts[s]; for (int i = orderedPtrAUIToCode.size() - 1; i > 0; i--) { String code = (String) orderedPtrAUIToCode.getValue(i); String codePrev = (String) orderedPtrAUIToCode.getValue(i - 1); stmt.setString(1, code); stmt.setString(2, codePrev); stmt.setString(3, aq.codingSchemeName); ResultSet results = stmt.executeQuery(); try { // Iterate through all relevant association links ... while (results.next()) { String multiAttributesKey = results .getString(SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY); String targetConceptCode = results.getString(stc_.targetEntityCodeOrId); String sourceConceptCode = results.getString(stc_.sourceEntityCodeOrId); String association = results.getString(stc_.entityCodeOrAssociationId); // If there is no key to correlate to the // multi-attributes table, // construct and add now. if (multiAttributesKey == null) { StringBuffer key = new StringBuffer().append(System.currentTimeMillis()) .append((int) Math.floor((Math.random() * 100000))).append(totalCount); multiAttributesKey = key.substring(0, Math.min(50, key.length())); updateMAK.setString(1, multiAttributesKey); updateMAK.setString(2, aq.codingSchemeName); updateMAK.setString(3, sourceConceptCode); updateMAK.setString(4, targetConceptCode); updateMAK.setString(5, association); updateMAK.execute(); } // Add a context qualifier to the multi-attributes // table. try { addEntityAssociationQualifierToEntityAssociation(aq.codingSchemeName, multiAttributesKey, aq.qualifierName, hcd); contextLinks++; } catch (SQLException e) { // Because we qualify all relationships along // the PTR and // the HCD is identical for siblings at the same // PTR some // exceptions with regards to identical keys // will come up. // We try to bypass altogether if the message // indicates duplication. // However, message text can vary based on the // database engine. // Rather than exit in error, log the message // and continue. if (!e.getMessage().contains("Duplicate")) { messages_.warn("Unable to add context qualifier to association.", e); } } } } finally { results.close(); } } } } finally { updateMAK.close(); getRelationship_1.close(); getRelationship_2.close(); } return contextLinks; }
From source file:com.krawler.spring.crm.emailMarketing.crmEmailMarketingController.java
public ModelAndView getUnAssignCampaignTarget(HttpServletRequest request, HttpServletResponse response) throws ServletException { JSONObject jobj = new JSONObject(); JSONArray jarr = new JSONArray(); try {/*from w ww .j a v a 2 s .c o m*/ HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("companyid", sessionHandlerImpl.getCompanyid(request)); requestParams.put("campID", request.getParameter("campID")); ArrayList filter_names = new ArrayList(); ArrayList filter_params = new ArrayList(); filter_names.add("deleted"); filter_params.add(0); filter_names.add("creator.company.companyID"); filter_params.add(sessionHandlerImpl.getCompanyid(request)); filter_names.add("saveflag"); filter_params.add(1); HashMap<String, Object> subRequestParams = new HashMap<String, Object>(); subRequestParams.put("allflag", true); ArrayList subfilter_names = new ArrayList(); ArrayList subfilter_params = new ArrayList(); subfilter_names.add("targetlist.deleted"); subfilter_params.add(0); subfilter_names.add("campaign.campaignid"); subfilter_params.add(request.getParameter("campID")); subfilter_names.add("deleted"); subfilter_params.add(0); subRequestParams.put("filter_names", subfilter_names); subRequestParams.put("filter_params", subfilter_params); KwlReturnObject kmsg = crmEmailMarketingDAOObj.getCampaignTarget(subRequestParams); Iterator ite = kmsg.getEntityList().iterator(); StringBuffer assTLID = new StringBuffer(); while (ite.hasNext()) { CampaignTarget obj = (CampaignTarget) ite.next(); assTLID.append("'" + obj.getTargetlist().getId() + "',"); } if (assTLID.length() > 0) { filter_names.add("NOTINid"); String ids = assTLID.substring(0, assTLID.length() - 1); filter_params.add(ids); } requestParams.put("filter_names", filter_names); requestParams.put("filter_params", filter_params); requestParams.put("allflag", true); kmsg = crmEmailMarketingDAOObj.getTargetList(requestParams); ite = kmsg.getEntityList().iterator(); while (ite.hasNext()) { TargetList obj = (TargetList) ite.next(); JSONObject jtemp = new JSONObject(); jtemp.put("listid", obj.getId()); jtemp.put("listname", obj.getName()); jarr.put(jtemp); } jobj.put("data", jarr); } catch (SessionExpiredException e) { logger.warn(e.getMessage(), e); } catch (ServiceException e) { logger.warn(e.getMessage(), e); } catch (JSONException e) { logger.warn(e.getMessage(), e); } return new ModelAndView("jsonView", "model", jobj.toString()); }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials, Set<StringMod> mods, boolean showCommas) { int pos = result.indexOf(".") - 1; if (pos < 0) { if (exponent != null && numSpecials == integerSpecials) pos = result.indexOf("E") - 1; else//from w w w .j a v a 2 s . c o m pos = result.length() - 1; } int strip; for (strip = 0; strip < pos; strip++) { char resultCh = result.charAt(strip); if (resultCh != '0' && resultCh != ',') break; } ListIterator<Special> it = numSpecials.listIterator(numSpecials.size()); boolean followWithComma = false; Special lastOutputIntegerDigit = null; int digit = 0; while (it.hasPrevious()) { char resultCh; if (pos >= 0) resultCh = result.charAt(pos); else { // If result is shorter than field, pretend there are leading zeros resultCh = '0'; } Special s = it.previous(); followWithComma = showCommas && digit > 0 && digit % 3 == 0; boolean zeroStrip = false; if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) { zeroStrip = s.ch == '?' && pos < strip; output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh)); lastOutputIntegerDigit = s; } if (followWithComma) { mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER)); followWithComma = false; } digit++; --pos; } StringBuffer extraLeadingDigits = new StringBuffer(); if (pos >= 0) { // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later ++pos; // pos was decremented at the end of the loop above when the iterator was at its end extraLeadingDigits = new StringBuffer(result.substring(0, pos)); if (showCommas) { while (pos > 0) { if (digit > 0 && digit % 3 == 0) extraLeadingDigits.insert(pos, ','); digit++; --pos; } } mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE)); } }
From source file:org.silverpeas.components.kmelia.servlets.KmeliaRequestRouter.java
/** * This method has to be implemented by the component request rooter it has to compute a * destination page// w w w.j a v a 2 s .c om * @param function The entering request function ( : "Main.jsp") * @param kmelia The component Session Control, build and initialised. * @param request The entering request. The request rooter need it to get parameters * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, KmeliaSessionController kmelia, HttpRequest request) { String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode; SilverpeasRole userRoleOnCurrentTopic = SilverpeasRole .from(kmelia.getUserTopicProfile(kmelia.getCurrentFolderId())); SilverpeasRole highestSilverpeasUserRoleOnCurrentTopic = null; if (userRoleOnCurrentTopic != null) { highestSilverpeasUserRoleOnCurrentTopic = SilverpeasRole.getHighestFrom(userRoleOnCurrentTopic); } try { if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.setKmaxMode(true); } request.setAttribute("KmaxMode", kmaxMode); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("validateClassification")) { String[] publicationIds = request.getParameterValues("pubid"); Collection<KmeliaPublication> publications = kmelia .getPublications(asPks(kmelia.getComponentId(), publicationIds)); request.setAttribute("Context", URLUtil.getApplicationURL()); request.setAttribute("PublicationsDetails", publications); destination = rootDestination + "validateImportedFilesClassification.jsp"; } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = kmelia.getHighestSilverpeasUserRole().getName(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if ("GoToTopic".equals(function)) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = NodePK.ROOT_NODE_ID; } } kmelia.setCurrentFolderId(topicId, true); request.setAttribute("CurrentFolderId", topicId); request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis()); request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled()); request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", kmelia.getUserDetail().isAccessGuest()); request.setAttribute("RightsOnTopicsEnabled", kmelia.isRightsOnTopicsEnabled()); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); request.setAttribute("PageIndex", kmelia.getIndexOfFirstPubToDisplay()); if (kmelia.isTreeviewUsed()) { destination = rootDestination + "treeview.jsp"; } else if (kmelia.isTreeStructure()) { destination = rootDestination + "oneLevel.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } else if ("GoToCurrentTopic".equals(function)) { if (!NodePK.ROOT_NODE_ID.equals(kmelia.getCurrentFolderId())) { request.setAttribute("Id", kmelia.getCurrentFolderId()); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if ("GoBackToResults".equals(function)) { request.setAttribute("SearchContext", kmelia.getSearchContext()); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.startsWith("searchResult")) { String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); String from = request.getParameter("From"); if ("Search".equals(from)) { // identify clearly access from global search // because same URL is used from portlet, permalink... request.setAttribute("SearchScope", SearchContext.GLOBAL); } if (type != null && ("Publication".equals(type) || "org.silverpeas.core.personalorganizer.model.TodoDetail".equals(type) || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) { KmeliaAuthorization security = new KmeliaAuthorization(kmelia.getOrganisationController()); try { PublicationDetail pub2Check = kmelia.getPublicationDetail(id); // If given PK defines a clone, change PK to master if (pub2Check.haveGotClone()) { // check if publication is really the master or the clone ? int pubId = Integer.parseInt(pub2Check.getId()); int cloneId = Integer.parseInt(pub2Check.getCloneId()); boolean clone = pubId > cloneId; if (clone) { id = pub2Check.getCloneId(); request.setAttribute("ForcedId", id); } } boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { processPath(kmelia, id); if ("Attachment".equals(type)) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if ("Document".equals(type)) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { // we have to find which page contains the right publication List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { KmeliaPublication publication = publications.get(p); if (id.equals(publication.getDetail().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); request.setAttribute("Id", kmelia.getCurrentFolderId()); destination = getDestination("GoToTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverLogger.getLogger(this).error("Document not found. {0}", new String[] { e.getMessage() }, e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if ("Node".equals(type)) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant slectionn la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", kmelia, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } catch (Exception e) { SilverLogger.getLogger(this).error("Document not found. {0}", new String[] { e.getMessage() }, e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if ("Wysiwyg".equals(type)) { if (id.startsWith("Node")) { id = id.substring("Node_".length(), id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", NodePK.ROOT_NODE_ID); destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); kmelia.setSessionPublication(kmeliaPublication); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverLogger.getLogger(this).error("Document not found. {0}", new String[] { e.getMessage() }, e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if ("ToUpdatePublicationHeader".equals(function)) { request.setAttribute("Action", "UpdateView"); destination = getDestination("ToPublicationHeader", kmelia, request); } else if ("ToPublicationHeader".equals(function)) { String action = (String) request.getAttribute("Action"); if ("UpdateView".equals(action)) { request.setAttribute("AttachmentsEnabled", false); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone()); setupRequestForSubscriptionNotificationSending(request, highestSilverpeasUserRoleOnCurrentTopic, kmelia.getCurrentFolderPK(), kmelia.getSessionPubliOrClone().getDetail()); } else if ("New".equals(action)) { // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); request.setAttribute("TaxonomyOK", true); request.setAttribute("ValidatorsOK", true); } request.setAttribute("Path", kmelia.getTopicPath(kmelia.getCurrentFolderId())); request.setAttribute("Profile", kmelia.getProfile()); destination = rootDestination + "publicationManager.jsp"; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(NodePK.ROOT_NODE_ID)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, 0, "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getCurrentFolder(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, 0, "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } boolean goToProfilesDefinition = false; if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic.setRightsDependsOn(rightsUsed); // process destination NodeDetail oldTopic = kmelia.getNodeHeader(id); if (oldTopic.getRightsDependsOn() != rightsUsed && rightsUsed != -1) { // rights dependency have changed and folder uses its own rights goToProfilesDefinition = true; } } kmelia.updateTopicHeader(topic, alertType); if (goToProfilesDefinition) { request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); KmeliaPublication kmeliaPublication = kmelia.getPublication(cloneId); kmelia.setSessionClone(kmeliaPublication); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("ValidationType", kmelia.getValidationType()); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); destination = rootDestination + "clone.jsp"; } else if ("ViewPublication".equals(function)) { String id = (String) request.getAttribute("ForcedId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } } if (!kmaxMode) { boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath || KmeliaHelper.isToValidateFolder(kmelia.getCurrentFolderId())) { processPath(kmelia, id); } else { processPath(kmelia, null); } } // view publication from global search ? Integer searchScope = (Integer) request.getAttribute("SearchScope"); if (searchScope == null) { if (kmelia.getSearchContext() != null) { request.setAttribute("SearchScope", SearchContext.LOCAL); } else { request.setAttribute("SearchScope", SearchContext.NONE); } } KmeliaPublication kmeliaPublication; if (StringUtil.isDefined(id)) { kmeliaPublication = kmelia.getPublication(id, true); // Check user publication access PublicationAccessController publicationAccessController = ServiceProvider .getService(PublicationAccessController.class); if (!publicationAccessController.isUserAuthorized(kmelia.getUserId(), kmeliaPublication.getPk())) { SilverLogger.getLogger(this).warn("Security alert from {0} with publication {1}", kmelia.getUserId(), id); return "/admin/jsp/accessForbidden.jsp"; } kmelia.setSessionPublication(kmeliaPublication); PublicationDetail pubDetail = kmeliaPublication.getDetail(); if (pubDetail.haveGotClone()) { KmeliaPublication clone = kmelia.getPublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { kmeliaPublication = kmelia.getSessionPublication(); id = kmeliaPublication.getDetail().getPK().getId(); } if (toolboxMode) { destination = getDestination("ToUpdatePublicationHeader", kmelia, request); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, kmeliaPublication.getDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management List<PublicationLink> links = kmeliaPublication.getCompleteDetail().getLinkList(); HashSet<String> linkedList = new HashSet<>(links.size()); for (PublicationLink link : links) { linkedList.add(link.getTarget().getId() + "-" + link.getTarget().getComponentInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("PubId", id); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication() && kmelia.getSessionClone() == null); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", kmelia.getValidationType()); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", kmelia.isWriterApproval()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // check is requested publication is an alias boolean alias = checkAlias(kmelia, kmeliaPublication); if (alias) { request.setAttribute("Profile", "user"); request.setAttribute("TaxonomyOK", false); request.setAttribute("ValidatorsOK", false); } else { request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } request.setAttribute("Rang", kmelia.getRang()); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size()); } else { request.setAttribute("NbPublis", 1); } putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia.getSingleAttachmentURLOfCurrentPublication(alias)); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId, alias)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId, alias)); } // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); // Last vistors area must be displayed or not ? final boolean lastVisitorsEnabled = kmelia.isLastVisitorsEnabled(); request.setAttribute("LastVisitorsEnabled", lastVisitorsEnabled); if (lastVisitorsEnabled) { request.setAttribute("LastAccess", kmelia.getLastAccess(kmeliaPublication.getPk())); } request.setAttribute("PublicationRatingsAllowed", kmelia.isPublicationRatingAllowed()); request.setAttribute("SeeAlsoEnabled", kmelia.isSeeAlsoEnabled()); // Subscription management setupRequestForSubscriptionNotificationSending(request, highestSilverpeasUserRoleOnCurrentTopic, kmelia.getCurrentFolderPK(), kmeliaPublication.getDetail()); destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // rcupration de la publication prcdente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // rcupration de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLUtil.getURL(URLUtil.CMP_CLIPBOARD, null, null) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLUtil.getURL(URLUtil.CMP_CLIPBOARD, null, null) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone().getDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication().getDetail()); } // Paramtres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); request.setAttribute("ForcedId", kmelia.getSessionPublication().getId()); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if ("ValidatePublication".equals(function)) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); destination = getDestination("ViewPublication", kmelia, request); } else { request.setAttribute("Action", "ValidationInProgress"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if ("Unvalidate".equals(function)) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", kmelia, request); } else { String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, kmelia, request); } else { destination = getDestination("ToUpdatePublicationHeader", kmelia, request); } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); String browseInfo = kmelia.getSessionPathString(); if (browseInfo != null && !browseInfo.contains(topic.getName())) { browseInfo += topic.getName(); } if (!StringUtil.isDefined(browseInfo)) { browseInfo = kmelia.getString("TopicWysiwyg"); } else { browseInfo += " > " + kmelia.getString("TopicWysiwyg"); } WysiwygRouting routing = new WysiwygRouting(); WysiwygRouting.WysiwygRoutingContext context = WysiwygRouting.WysiwygRoutingContext .fromComponentSessionController(kmelia).withBrowseInfo(browseInfo) .withContributionId( ContributionIdentifier.from(kmelia.getComponentId(), "Node_" + subTopicId, NODE)) .withContentLanguage(kmelia.getCurrentLanguage()) .withComeBackUrl(URLUtil.getApplicationURL() + URLUtil.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag); destination = routing.getWysiwygEditorPath(context, request); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("Id"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootPK", new NodePK(topicId, kmelia.getComponentId())); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { request.setAttribute("Action", "New"); request.setAttribute("ExtraForm", kmelia.getXmlFormForPublications()); PublicationDetail volatilePublication = kmelia.prepareNewPublication(); request.setAttribute("VolatilePublication", volatilePublication); PagesContext extraFormPageContext = new PagesContext(); extraFormPageContext.setUserId(kmelia.getUserId()); extraFormPageContext.setComponentId(kmelia.getComponentId()); extraFormPageContext.setObjectId(volatilePublication.getPK().getId()); extraFormPageContext.setNodeId(kmelia.getCurrentFolderId()); extraFormPageContext.setLanguage(kmelia.getLanguage()); request.setAttribute("ExtraFormPageContext", extraFormPageContext); destination = getDestination("ToPublicationHeader", kmelia, request); } else if (function.equals("ManageSubscriptions")) { destination = kmelia.manageSubscriptions(); } else if (function.equals("AddPublication")) { List<FileItem> parameters = request.getFileItems(); // create publication String positions = FileUploadUtil.getParameter(parameters, "KmeliaPubPositions"); PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification(); if (StringUtil.isDefined(positions)) { withClassification = PdcClassificationEntity.fromJSON(positions); } PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail, withClassification); if (kmelia.isReminderUsed()) { PublicationDetail pubDetailCreated = kmelia.getPublicationDetail(newPubId); kmelia.addPublicationReminder(pubDetailCreated, parameters); } // create thumbnail if exists boolean newThumbnail = ThumbnailController .processThumbnail(new ResourceReference(newPubId, kmelia.getComponentId()), parameters); //process files Collection<UploadedFile> attachments = request.getUploadedFiles(); kmelia.addUploadedFilesToPublication(attachments, pubDetail); String volatileId = FileUploadUtil.getParameter(parameters, "KmeliaPubVolatileId"); if (StringUtil.isDefined(volatileId)) { //process extra form kmelia.saveXMLFormToPublication(pubDetail, parameters, false); } // force indexation to add thumbnail and attachments to publication index if ((newThumbnail || !attachments.isEmpty()) && pubDetail.isIndexable()) { kmelia.getPublicationService().createIndex(pubDetail.getPK()); } request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } else if ("UpdatePublication".equals(function)) { List<FileItem> parameters = request.getFileItems(); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String pubId = pubDetail.getPK().getId(); ThumbnailController.processThumbnail(new ResourceReference(pubId, kmelia.getComponentId()), parameters); kmelia.updatePublication(pubDetail); if (kmelia.isReminderUsed()) { kmelia.updatePublicationReminder(pubId, parameters); } if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", pubId); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("SelectValidator")) { String formElementName = request.getParameter("FormElementName"); String formElementId = request.getParameter("FormElementId"); String folderId = request.getParameter("FolderId"); destination = kmelia.initUPToSelectValidator(formElementName, formElementId, folderId); } else if (function.equals("PublicationPaths")) { PublicationDetail publication = kmelia.getSessionPublication().getDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); if (toolboxMode) { request.setAttribute("Topics", kmelia.getAllTopics()); } else { List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("Components", kmelia.getComponents(aliases)); } destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcment t chargs List<Alias> oldAliases = kmelia.getAliases(); for (Alias oldAlias : oldAliases) { if (!loadedComponentIds.contains(oldAlias.getInstanceId())) { // le composant de l'alias n'a pas t charg aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); //noinspection unchecked HashSet<String> list = (HashSet) request.getSession() .getAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportTopic")) { String topicId = request.getParameter("TopicId"); boolean exportFullApp = !StringUtil.isDefined(topicId) || NodePK.ROOT_NODE_ID.equals(topicId); if (kmaxMode) { if (exportFullApp) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { destination = getDestination("KmaxExportPublications", kmelia, request); } } else { // build an exploitable list by importExportPeas final List<WAAttributeValuePair> publicationsIds; if (exportFullApp) { publicationsIds = kmelia.getAllVisiblePublications(); } else { publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootPK", new NodePK(topicId, kmelia.getComponentId())); // Go to importExportPeas destination = "/RimportExportPeas/jsp/SelectExportMode"; } } else if (function.equals("ExportPublications")) { String selectedIds = request.getParameter("SelectedIds"); String notSelectedIds = request.getParameter("NotSelectedIds"); List<PublicationPK> pks = kmelia.processSelectedPublicationIds(selectedIds, notSelectedIds); List<WAAttributeValuePair> publicationIds = new ArrayList<WAAttributeValuePair>(); for (PublicationPK pk : pks) { publicationIds.add(new WAAttributeValuePair(pk.getId(), pk.getInstanceId())); } request.setAttribute("selectedResultsWa", publicationIds); request.setAttribute("RootPK", new NodePK(kmelia.getCurrentFolderId(), kmelia.getComponentId())); kmelia.resetSelectedPublicationPKs(); // Go to importExportPeas destination = "/RimportExportPeas/jsp/SelectExportMode"; } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (WysiwygController.haveGotWysiwyg(kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId(), kmelia.getCurrentLanguage())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else { // XML template request.setAttribute("Name", modelId); destination = getDestination("GoToXMLForm", kmelia, request); } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { setTemplatesUsedIntoRequest(kmelia, request); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication().getDetail()); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { request.setAttribute("XMLForms", kmelia.getForms()); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { kmelia.setModelUsed(request.getParameterValues("modelChoice")); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if ("ChangeTemplate".equals(function)) { kmelia.removePublicationContent(); destination = getDestination("ToPubliContent", kmelia, request); } else if ("ToWysiwyg".equals(function)) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication PublicationDetail publication = kmelia.getSessionPubliOrClone().getDetail(); String browseInfo; if (kmaxMode) { browseInfo = publication.getName(); } else { browseInfo = kmelia.getSessionPathString(); if (StringUtil.isDefined(browseInfo)) { browseInfo += " > "; } browseInfo += publication.getName(kmelia.getCurrentLanguage()); } // Subscription management setupRequestForSubscriptionNotificationSending(request, highestSilverpeasUserRoleOnCurrentTopic, kmelia.getCurrentFolderPK(), publication); WysiwygRouting routing = new WysiwygRouting(); WysiwygRouting.WysiwygRoutingContext context = WysiwygRouting.WysiwygRoutingContext .fromComponentSessionController(kmelia).withBrowseInfo(browseInfo) .withContributionId(ContributionIdentifier.from(kmelia.getComponentId(), publication.getId(), publication.getContributionType())) .withContentLanguage(checkLanguage(kmelia, publication)) .withComeBackUrl(URLUtil.getApplicationURL() + kmelia.getComponentUrl() + "FromWysiwyg?PubId=" + publication.getId()) .withIndexation(false); destination = routing.getWysiwygEditorPath(context, request); } else if ("FromWysiwyg".equals(function)) { String id = request.getParameter("PubId"); if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getDetail().getPK().getId())) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = (String) request.getAttribute("Name"); if (!StringUtil.isDefined(xmlFormName)) { xmlFormName = request.getParameter("Name"); } setXMLUpdateForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone().getDetail()); // template can be changed only if current topic is using at least two templates setTemplatesUsedIntoRequest(kmelia, request); @SuppressWarnings("unchecked") Collection<PublicationTemplate> templates = (Collection<PublicationTemplate>) request .getAttribute("XMLForms"); boolean wysiwygUsable = (Boolean) request.getAttribute("WysiwygValid"); request.setAttribute("IsChangingTemplateAllowed", templates.size() >= 2 || (!templates.isEmpty() && wysiwygUsable)); setupRequestForSubscriptionNotificationSending(request, highestSilverpeasUserRoleOnCurrentTopic, kmelia.getCurrentFolderPK(), kmelia.getSessionPubliOrClone().getDetail()); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { List<FileItem> items = request.getFileItems(); kmelia.saveXMLForm(items, true); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.startsWith("ToOrderPublications")) { List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if ("ViewTopicProfiles".equals(function)) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } if (!(kmelia.isTopicAdmin(id) || kmelia.isUserComponentAdmin())) { SilverLogger.getLogger(this).warn("Security alert from {0}", kmelia.getUserId()); return "/admin/jsp/accessForbidden.jsp"; } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, true, 3)); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); String[] userIds = StringUtil.split(request.getParameter("UserPanelCurrentUserIds"), ','); String[] groupIds = StringUtil.split(request.getParameter("UserPanelCurrentGroupIds"), ','); try { kmelia.initUserPanelForTopicProfile(role, nodeId, groupIds, userIds); } catch (Exception e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } destination = Selection.getSelectionURL(); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); String[] userIds = StringUtil.split(request.getParameter("roleItems" + "UserPanelCurrentUserIds"), ','); String[] groupIds = StringUtil.split(request.getParameter("roleItems" + "UserPanelCurrentGroupIds"), ','); if (kmelia.isTopicAdmin(nodeId) || kmelia.isUserComponentAdmin()) { kmelia.updateTopicRole(role, nodeId, groupIds, userIds); } else { SilverLogger.getLogger(this).warn("Security alert from {0}", kmelia.getUserId()); } destination = getDestination("ViewTopicProfiles", kmelia, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } /** * ************************* * Kmax mode *********************** */ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, 0, "X"); axis.setCreationDate(DateUtil.today2SQLDate()); axis.setCreatorId(kmelia.getUserId()); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, 0, "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, 0, "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", kmelia, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, 0, "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxViewUnbalanced")) { List<KmeliaPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<KmeliaPublication> publications = (List<KmeliaPublication>) basket.getKmeliaPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); List<String> combination = kmelia.getCombination(axisValuesStr); List<KmeliaPublication> publications; if (StringUtil.isDefined(timeCriteria) && !"X".equals(timeCriteria)) { publications = kmelia.search(combination, Integer.parseInt(timeCriteria)); } else { publications = kmelia.search(combination); } kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { LocalizationBundle timeSettings = ResourceLocator .getLocalizationBundle("org.silverpeas.kmelia.multilang.timeAxisBundle"); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { String localizedCriteria = timeSettings.getString(kmelia.getSessionTimeCriteria()); if (localizedCriteria == null || localizedCriteria.trim().isEmpty()) { localizedCriteria = ""; } timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + localizedCriteria; } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; } else if ("statistics".equals(function)) { destination = rootDestination + STATISTIC_REQUEST_HANDLER.handleRequest(request, function, kmelia); } else if ("statSelectionGroup".equals(function)) { destination = STATISTIC_REQUEST_HANDLER.handleRequest(request, function, kmelia); } else if ("SetPublicationValidator".equals(function)) { String userIds = request.getParameter("ValideurId"); kmelia.setPublicationValidator(userIds); destination = getDestination("ViewPublication", kmelia, request); } else { destination = rootDestination + function; } if (profileError) { destination = ResourceLocator.getGeneralSettingBundle().getString("sessionTimeout"); } } catch (Exception exceAll) { request.setAttribute("javax.servlet.jsp.jspException", exceAll); return "/admin/jsp/errorpageMain.jsp"; } return destination; }