List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:edu.cornell.mannlib.vitro.webapp.controller.FedoraDatastreamController.java
@Override public void doPost(HttpServletRequest rawRequest, HttpServletResponse res) throws ServletException, IOException { try {// w ww . j av a2 s.c o m VitroRequest req = new VitroRequest(rawRequest); if (req.hasFileSizeException()) { throw new FdcException("Size limit exceeded: " + req.getFileSizeException().getLocalizedMessage()); } if (!req.isMultipart()) { throw new FdcException("Must POST a multipart encoded request"); } //check if fedora is on line OntModel sessionOntModel = ModelAccess.on(getServletContext()).getOntModel(); synchronized (FedoraDatastreamController.class) { if (fedoraUrl == null) { setup(sessionOntModel, getServletContext()); if (fedoraUrl == null) throw new FdcException("Connection to the file repository is " + "not setup correctly. Could not read fedora.properties file"); } else { if (!canConnectToFedoraServer()) { fedoraUrl = null; throw new FdcException("Could not connect to Fedora."); } } } FedoraClient fedora; try { fedora = new FedoraClient(fedoraUrl, adminUser, adminPassword); } catch (MalformedURLException e) { throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl); } FedoraAPIM apim; try { apim = fedora.getAPIM(); } catch (Exception e) { throw new FdcException("could not create fedora APIM:" + e.getMessage()); } //get the parameters from the request String pId = req.getParameter("pid"); String dsId = req.getParameter("dsid"); String fileUri = req.getParameter("fileUri"); boolean useNewName = false; if ("true".equals(req.getParameter("useNewName"))) { useNewName = true; } if (pId == null || pId.length() == 0) throw new FdcException("Your form submission did not contain " + "enough information to complete your request.(Missing pid parameter)"); if (dsId == null || dsId.length() == 0) throw new FdcException("Your form submission did not contain " + "enough information to complete your request.(Missing dsid parameter)"); if (fileUri == null || fileUri.length() == 0) throw new FdcException("Your form submission did not contain " + "enough information to complete your request.(Missing fileUri parameter)"); FileItem fileRes = req.getFileItem("fileRes"); if (fileRes == null) throw new FdcException("Your form submission did not contain " + "enough information to complete your request.(Missing fileRes)"); //check if file individual has a fedora:PID for a data stream VitroRequest vreq = new VitroRequest(rawRequest); IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao(); Individual fileEntity = iwDao.getIndividualByURI(fileUri); //check if logged in //TODO: check if logged in //check if user is allowed to edit datastream //TODO:check if can edit datastream //check if digital object and data stream exist in fedora Datastream ds = apim.getDatastream(pId, dsId, null); if (ds == null) throw new FdcException( "There was no datastream in the " + "repository for " + pId + " " + DEFAULT_DSID); //upload to temp holding area String originalName = fileRes.getName(); String name = originalName.replaceAll("[,+\\\\/$%^&*#@!<>'\"~;]", "_"); name = name.replace("..", "_"); name = name.trim().toLowerCase(); String saveLocation = baseDirectoryForFiles + File.separator + name; String savedName = name; int next = 0; boolean foundUnusedName = false; while (!foundUnusedName) { File test = new File(saveLocation); if (test.exists()) { next++; savedName = name + '(' + next + ')'; saveLocation = baseDirectoryForFiles + File.separator + savedName; } else { foundUnusedName = true; } } File uploadedFile = new File(saveLocation); try { fileRes.write(uploadedFile); } catch (Exception ex) { log.error("Unable to save POSTed file. " + ex.getMessage()); throw new FdcException("Unable to save file to the disk. " + ex.getMessage()); } //upload to temp area on fedora File file = new File(saveLocation); String uploadFileUri = fedora.uploadFile(file); // System.out.println("Fedora upload temp = upload file uri is " + uploadFileUri); String md5 = md5hashForFile(file); md5 = md5.toLowerCase(); //make change to data stream on fedora apim.modifyDatastreamByReference(pId, dsId, null, null, fileRes.getContentType(), null, uploadFileUri, "MD5", null, null, false); String checksum = apim.compareDatastreamChecksum(pId, dsId, null); //update properties like checksum, file size, and content type WebappDaoFactory wdf = vreq.getWebappDaoFactory(); DataPropertyStatement dps = null; DataProperty contentType = wdf.getDataPropertyDao().getDataPropertyByURI(this.contentTypeProperty); if (contentType != null) { wdf.getDataPropertyStatementDao() .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, contentType); dps = new DataPropertyStatementImpl(); dps.setIndividualURI(fileEntity.getURI()); dps.setDatapropURI(contentType.getURI()); dps.setData(fileRes.getContentType()); wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps); } DataProperty fileSize = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileSizeProperty); if (fileSize != null) { wdf.getDataPropertyStatementDao() .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileSize); dps = new DataPropertyStatementImpl(); dps.setIndividualURI(fileEntity.getURI()); dps.setDatapropURI(fileSize.getURI()); dps.setData(Long.toString(fileRes.getSize())); wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps); //System.out.println("Updated file size with " + fileRes.getSize()); } DataProperty checksumDp = wdf.getDataPropertyDao().getDataPropertyByURI(this.checksumDataProperty); if (checksumDp != null) { //System.out.println("Checksum data property is also not null"); wdf.getDataPropertyStatementDao() .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, checksumDp); dps = new DataPropertyStatementImpl(); dps.setIndividualURI(fileEntity.getURI()); dps.setDatapropURI(checksumDp.getURI()); dps.setData(checksum); wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps); } //I'm leaving if statement out for now as the above properties are obviously being replaced as well //if( "true".equals(useNewName)){ //Do we need to encapuslate in this if OR is this path always for replacing a file //TODO: Put in check to see if file name has changed and only execute these statements if file name has changed DataProperty fileNameProperty = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileNameProperty); if (fileNameProperty != null) { wdf.getDataPropertyStatementDao() .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileNameProperty); dps = new DataPropertyStatementImpl(); dps.setIndividualURI(fileEntity.getURI()); dps.setDatapropURI(fileNameProperty.getURI()); dps.setData(originalName); //This follows the pattern of the original file upload - the name returned from the uploaded file object wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps); //System.out.println("File name property is not null = " + fileNameProperty.getURI() + " updating to " + originalName); } else { //System.out.println("file name property is null"); } //Need to also update the check sum node - how would we do that //Find checksum node related to this particular file uri, then go ahead and update two specific fields List<ObjectPropertyStatement> csNodeStatements = fileEntity.getObjectPropertyMap() .get(this.checksumNodeProperty).getObjectPropertyStatements(); if (csNodeStatements.size() == 0) { System.out.println("No object property statements correspond to this property"); } else { ObjectPropertyStatement cnodeStatement = csNodeStatements.get(0); String cnodeUri = cnodeStatement.getObjectURI(); //System.out.println("Checksum node uri is " + cnodeUri); Individual checksumNodeObject = iwDao.getIndividualByURI(cnodeUri); DataProperty checksumDateTime = wdf.getDataPropertyDao() .getDataPropertyByURI(this.checksumNodeDateTimeProperty); if (checksumDateTime != null) { String newDatetime = sessionOntModel.createTypedLiteral(new DateTime()).getString(); //Review how to update date time wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty( checksumNodeObject, checksumDateTime); dps = new DataPropertyStatementImpl(); dps.setIndividualURI(checksumNodeObject.getURI()); dps.setDatapropURI(checksumDateTime.getURI()); dps.setData(newDatetime); wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps); } DataProperty checksumNodeValue = wdf.getDataPropertyDao() .getDataPropertyByURI(this.checksumDataProperty); if (checksumNodeValue != null) { wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty( checksumNodeObject, checksumNodeValue); dps = new DataPropertyStatementImpl(); dps.setIndividualURI(checksumNodeObject.getURI()); dps.setDatapropURI(checksumNodeValue.getURI()); dps.setData(checksum); //Same as fileName above - change if needed wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps); } } //Assumes original entity name is equal to the location - as occurs with regular file upload String originalEntityName = fileEntity.getName(); if (originalEntityName != originalName) { //System.out.println("Setting file entity to name of uploaded file"); fileEntity.setName(originalName); } else { //System.out.println("Conditional for file entity name and uploaded name is saying same"); } iwDao.updateIndividual(fileEntity); //} req.setAttribute("fileUri", fileUri); req.setAttribute("originalFileName", fileEntity.getName()); req.setAttribute("checksum", checksum); if ("true".equals(useNewName)) { req.setAttribute("useNewName", "true"); req.setAttribute("newFileName", originalName); } else { req.setAttribute("newFileName", fileEntity.getName()); } //forward to form req.setAttribute("bodyJsp", "/fileupload/datastreamModificationSuccess.jsp"); RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP); rd.forward(req, res); } catch (FdcException ex) { rawRequest.setAttribute("errors", ex.getMessage()); RequestDispatcher rd = rawRequest.getRequestDispatcher("/edit/fileUploadError.jsp"); rd.forward(rawRequest, res); return; } }
From source file:it.infn.ct.wrf.Wrf.java
public String[] uploadSettings(ActionRequest actionRequest, ActionResponse actionResponse, String username) { String[] _Parameters = new String[7]; boolean status; // Check that we have a file upload request boolean isMultipart = PortletFileUpload.isMultipartContent(actionRequest); if (isMultipart) { // Create a factory for disk-based file items. DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constrains File _Repository = new File("/tmp"); if (!_Repository.exists()) status = _Repository.mkdirs(); factory.setRepository(_Repository); // Create a new file upload handler. PortletFileUpload upload = new PortletFileUpload(factory); try {//from www .j av a2 s . com // Parse the request List items = upload.parseRequest(actionRequest); // Processing items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String timeStamp = dateFormat.format(Calendar.getInstance().getTime()); // Processing a regular form field if (item.isFormField()) { if (fieldName.equals("wrf_textarea_OCTAVE")) { _Parameters[0] = _Repository + "/" + timeStamp + "_" + username + ".m"; // Store the textarea in a ASCII file storeString(_Parameters[0], item.getString()); } if (fieldName.equals("wrf_textarea_R")) { _Parameters[0] = _Repository + "/" + timeStamp + "_" + username + ".r"; // Store the textarea in a ASCII file storeString(_Parameters[0], item.getString()); } if (fieldName.equals("wrftype")) _Parameters[1] = item.getString(); if (fieldName.equals("wrf_CR")) _Parameters[2] = item.getString(); if (fieldName.equals("wrfvmtemplate")) _Parameters[5] = item.getString(); if (fieldName.equals("wrf_vmname")) _Parameters[6] = item.getString(); } else { // Processing a file upload if (fieldName.equals("wrf_file_OCTAVE") || fieldName.equals("wrf_file_R")) { log.info("\n- Uploading the following user's file: " + "\n[ " + item.getName() + " ]" + "\n[ " + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]"); // Writing the file to disk String uploadFile = _Repository + "/" + timeStamp + "_" + username + "_" + item.getName(); log.info("\n- Writing the user's file: [ " + uploadFile.toString() + " ] to disk"); item.write(new File(uploadFile)); _Parameters[0] = uploadFile; } } if (fieldName.equals("EnableNotification")) _Parameters[3] = item.getString(); if (fieldName.equals("wrf_desc")) if (item.getString().equals("Please, insert here a description for your run")) _Parameters[4] = "Cloud Simulation Started"; else _Parameters[4] = item.getString(); } // end while } catch (FileUploadException ex) { Logger.getLogger(Wrf.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(Wrf.class.getName()).log(Level.SEVERE, null, ex); } } return _Parameters; }
From source file:com.stratelia.webactiv.kmelia.servlets.KmeliaRequestRouter.java
/** * This method has to be implemented by the component request rooter it has to compute a * destination page//from w w w. j av a 2 s .c o m * * * @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) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode; try { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", kmaxMode); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); 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", URLManager.getApplicationURL()); request.setAttribute("PublicationsDetails", publications); destination = rootDestination + "validateImportedFilesClassification.jsp"; } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = kmelia.getUserRoleLevel(); 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); resetWizard(kmelia); request.setAttribute("CurrentFolderId", topicId); request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis()); request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled()); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", kmelia.isTopicHaveUpdateChainDescriptor()); 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")) { resetWizard(kmelia); 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) || "com.stratelia.webactiv.calendar.backbone.TodoDetail".equals(type) || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganisationController()); try { 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) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + 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) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + 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) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if ("ToUpdatePublicationHeader".equals(function)) { request.setAttribute("Action", "UpdateView"); destination = getDestination("publicationManager.jsp", kmelia, request); } else if ("publicationManager.jsp".equals(function)) { String action = (String) request.getAttribute("Action"); if ("UpdateView".equals(action)) { request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone()); } else if ("New".equals(action)) { request.setAttribute("TaxonomyOK", true); request.setAttribute("ValidatorsOK", true); } request.setAttribute("Wizard", kmelia.getWizard()); 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(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, null, null, null, "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, null, null, null, "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) { // rights dependency have changed if (rightsUsed != -1) { // 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("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 = 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); 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 Collection<ForeignPK> links = kmeliaPublication.getCompleteDetail().getLinkList(); HashSet<String> linkedList = new HashSet<String>(links.size()); for (ForeignPK link : links) { linkedList.add(link.getId() + "-" + link.getInstanceId()); } // 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(id)); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // check is requested publication is an alias checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("TaxonomyOK", false); request.setAttribute("ValidatorsOK", false); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } request.setAttribute("Wizard", kmelia.getWizard()); 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.getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); // option Actualits dcentralises request.setAttribute("NewsManage", kmelia.isNewsManage()); if (kmelia.isNewsManage()) { request.setAttribute("DelegatedNews", kmelia.getDelegatedNews(id)); request.setAttribute("IsBasket", NodePK.BIN_NODE_ID.equals(kmelia.getCurrentFolderId())); } request.setAttribute("LastAccess", kmelia.getLastAccess(kmeliaPublication.getPk())); request.setAttribute("PublicationRatingsAllowed", kmelia.isPublicationRatingAllowed()); 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 = URLManager.getURL(URLManager.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 = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramtre du wizard request.setAttribute("Wizard", kmelia.getWizard()); 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 du wizard setWizardParams(request, kmelia); // 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(); 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(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); 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(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); 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); request.setAttribute("PublicationToSuspend", pubDetail); 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); request.setAttribute("SpaceId", kmelia.getSpaceId()); request.setAttribute("SpaceName", URLEncoder.encode(kmelia.getSpaceLabel(), CharEncoding.UTF_8)); request.setAttribute("ComponentId", kmelia.getComponentId()); request.setAttribute("ComponentName", URLEncoder.encode(kmelia.getComponentLabel(), CharEncoding.UTF_8)); 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"); } request.setAttribute("BrowseInfo", browseInfo); request.setAttribute("ObjectId", "Node_" + subTopicId); request.setAttribute("Language", kmelia.getLanguage()); request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); request.setAttribute("ReturnUrl", URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag); destination = "/wysiwyg/jsp/htmlEditor.jsp"; } 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("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias String pubId = request.getParameter("PubId"); KmeliaPublication kmeliaPublication = kmelia.getSessionPublication(); if (StringUtil.isDefined(pubId)) { kmeliaPublication = kmelia.getPublication(pubId); kmelia.setSessionPublication(kmeliaPublication); } checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramtres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); if (pubIds != null) { List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); for (String pubId : pubIds) { StringTokenizer tokens = new StringTokenizer(pubId, "-"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); // removing deleted pks from session Set<String> list = (Set<String>) request.getSession() .getAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY); if (list != null) { list.remove(pubId); } } if (!infoLinks.isEmpty()) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } } destination = getDestination("SeeAlso", kmelia, request); } 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 SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); 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"); destination = getDestination("publicationManager.jsp", 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, "Positions"); PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification(); if (StringUtil.isDefined(positions)) { withClassification = PdcClassificationEntity.fromJSON(positions); } PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail, withClassification); // create thumbnail if exists boolean newThumbnail = ThumbnailController.processThumbnail( new ForeignPK(newPubId, kmelia.getComponentId()), PublicationDetail.getResourceType(), parameters); // force indexation to taking into account new thumbnail if (newThumbnail && pubDetail.isIndexable()) { kmelia.getPublicationBm().createIndex(pubDetail.getPK()); } request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { KmeliaPublication kmeliaPublication = kmelia.getPublication(newPubId); kmelia.setSessionPublication(kmeliaPublication); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { 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 id = pubDetail.getPK().getId(); ThumbnailController.processThumbnail(new ForeignPK(id, kmelia.getComponentId()), PublicationDetail.getResourceType(), parameters); kmelia.updatePublication(pubDetail); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("PublicationPaths")) { // paramtre du wizard request.setAttribute("Wizard", kmelia.getWizard()); 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]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); 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 SilverTrace.info("kmelia", "KmeliaRequestRouter.ExportTopic", "root.MSG_PARAM_VALUE", "topicId =" + topicId); 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 (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else 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 = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (StringUtil.isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", 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()); // Paramtres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { request.setAttribute("XMLForms", kmelia.getForms()); // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } 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(); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("SpaceId", kmelia.getSpaceId()); request.setAttribute("SpaceName", URLEncoder.encode(kmelia.getSpaceLabel(), CharEncoding.UTF_8)); request.setAttribute("ComponentId", kmelia.getComponentId()); request.setAttribute("ComponentName", URLEncoder.encode(kmelia.getComponentLabel(), CharEncoding.UTF_8)); if (kmaxMode) { request.setAttribute("BrowseInfo", publication.getName()); } else { request.setAttribute("BrowseInfo", kmelia.getSessionPathString() + " > " + publication.getName()); } request.setAttribute("ObjectId", publication.getId()); request.setAttribute("Language", kmelia.getLanguage()); request.setAttribute("ContentLanguage", checkLanguage(kmelia, publication)); request.setAttribute("ReturnUrl", URLManager.getApplicationURL() + kmelia.getComponentUrl() + "FromWysiwyg?PubId=" + publication.getId()); request.setAttribute("UserId", kmelia.getUserId()); request.setAttribute("IndexIt", "false"); destination = "/wysiwyg/jsp/htmlEditor.jsp"; } else if ("FromWysiwyg".equals(function)) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { 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("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getCompleteDetail()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // Paramtres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); int imageOrder = 0; boolean imageTrouble = false; List<FileItem> parameters = request.getFileItems(); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); for (FileItem item : parameters) { if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { String theText = item.getString(); int textOrder = Integer .parseInt(item.getFieldName().substring(8, item.getFieldName().length())); textDetails.add(new InfoTextDetail(null, Integer.toString(textOrder), null, theText)); } else if (!item.isFormField()) { String logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { if (!FileUtil.isWindows()) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = FilenameUtils.getName(logicalName); String physicalName = Long.toString(System.currentTimeMillis()) + "." + FilenameUtils.getExtension(logicalName); String mimeType = item.getContentType(); long size = item.getSize(); File dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separatorChar + physicalName); if (FileUtil.isImage(logicalName)) { item.write(dir); imageOrder++; if (size > 0L) { imageDetails.add(new InfoImageDetail(null, Integer.toString(imageOrder), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } InfoDetail infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); if (!StringUtil.isDefined(xmlFormName)) { xmlFormName = (String) request.getAttribute("Name"); } setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone().getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); // 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)); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = request.getFileItems(); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); String xmlFormShortName; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf('/') + 1, xmlFormName.indexOf('.')); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager() .getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia.getComponentId(), kmelia.getUserId()); context.setEncoding(CharEncoding.UTF_8); if (!kmaxMode) { context.setNodeId(kmelia.getCurrentFolderId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { 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 (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } 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"); } 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"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", kmelia, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } else if (function.equals("SuggestDelegatedNews")) { String pubId = kmelia.addDelegatedNews(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } /** * ************************* * 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, DateUtil.today2SQLDate(), kmelia.getUserId(), null, "0", "X"); // 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, null, null, null, "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, null, null, null, "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, null, null, null, "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"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + 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); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); 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")) { setWizardParams(request, kmelia); 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"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + 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())) { ResourceLocator timeSettings = new ResourceLocator( "org.silverpeas.kmelia.multilang.timeAxisBundle", kmelia.getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } 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 + statisticRequestHandler.handleRequest(request, function, kmelia); } else if ("statSelectionGroup".equals(function)) { destination = statisticRequestHandler.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 = GeneralPropertiesManager.getString("sessionTimeout"); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java
/** * Add a file in _fileList/*from ww w .ja v a 2 s . co m*/ * @param request HttpServletRequest * @return ret errorMessage */ private String addFileToFileList(HttpServletRequest request) { String ret = ""; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(PARAMETER_FILE); if ((StringUtils.isNotEmpty(request.getParameter(PARAMETER_FILE_TITLE))) && (StringUtils.isNotEmpty(request.getParameter(PARAMETER_FILE_NAME))) && (fileItem.get() != null)) { File file = new File(); PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); String name = fileItem.getName(); String type = name.substring(name.lastIndexOf(".") + 1).toUpperCase(); //Search files with same name int nNumVersion = Integer.parseInt(request.getParameter(PARAMETER_VERSION_NUM)); String strFileDBName = PluUtils.getFileNameForDB(request.getParameter(PARAMETER_FILE_NAME), String.valueOf(nNumVersion)); FileFilter fileFilter = new FileFilter(); fileFilter.setName(strFileDBName); List<File> listFileByName = _fileServices.findByFilter(fileFilter, new AtomeFilter()); //If a file with the same name exist in DB or a new atome file have the same name : error if (!listFileByName.isEmpty()) { Object[] args = { "", request.getParameter(PARAMETER_FILE_NAME) }; ret = this.getMessageJsp(request, MESSAGE_ERROR_FILE_CREATE_NAME, args, "jsp/admin/plugins/plu/file/JoinFile.jsp", null); } for (File fileTest : _fileList) { if (fileTest.getName().equals(request.getParameter(PARAMETER_FILE_NAME))) { Object[] args = { "", request.getParameter(PARAMETER_FILE_NAME) }; ret = this.getMessageJsp(request, MESSAGE_ERROR_FILE_CREATE_NAME, args, "jsp/admin/plugins/plu/file/JoinFile.jsp", null); } } if (StringUtils.isEmpty(ret)) { file.setName(request.getParameter(PARAMETER_FILE_NAME).replace(" ", "-")); file.setTitle(request.getParameter(PARAMETER_FILE_TITLE)); file.setUtilisation(request.getParameter(PARAMETER_FILE_UTILISATION).charAt(0)); file.setFile(physicalFile.getValue()); file.setMimeType(type); file.setSize((int) fileItem.getSize()); _fileList.add(file); } } else if (StringUtils.isNotEmpty(request.getParameter("joinFile"))) { if (request.getParameter("joinFile").equals("true")) { ret = this.getMessageJsp(request, MESSAGE_ERROR_REQUIRED_FIELD, null, "jsp/admin/plugins/plu/file/JoinFile.jsp", null); } } return ret; }
From source file:Controlador.Contr_Seleccion.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .j av a2s . co m*/ * * @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 { /*Se detalla el contenido que tendra el servlet*/ response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); /*Se crea una variable para la sesion*/ HttpSession session = request.getSession(true); boolean b; try { /*Se declaran las variables necesarias*/ Cls_Seleccion sel = new Cls_Seleccion(); String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti; String urlsalidaimg; urlsalidaimg = "/media/santiago/Santiago/IMGTE/"; //urlsalidaimg = "D:\\IMGTE\\"; String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Seleccion"); /*FileItemFactory es una interfaz para crear FileItem*/ FileItemFactory file_factory = new DiskFileItemFactory(); /*ServletFileUpload esta clase convierte los input file a FileItem*/ ServletFileUpload servlet_up = new ServletFileUpload(file_factory); /*sacando los FileItem del ServletFileUpload en una lista */ servlet_up.setHeaderEncoding("UTF-8"); List items = servlet_up.parseRequest(request); Iterator it = items.iterator(); /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/ while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField()) { //Plain request parameters will come here. String name = item.getFieldName(); if (name.equals("Codigo")) { /*Se guarda el campo en la clase*/ sel.setCodigo(item.getString()); } else if (name.equals("Nombre")) { /** * Se guarda el campo en la clase */ sel.setNombre(item.getString()); } else if (name.equals("Tipo")) { /** * Se guarda el campo en la clase */ sel.setTipo(item.getString()); } else if (name.equals("Estado")) { /** * Se guarda el campo en la clase */ sel.setEstado(item.getString()); } else if (name.equals("RegistrarSeleccion")) { /*Se evalua si se mando una iamgen, cuando se va a registrar un evento*/ if (!sel.getImagen().equals("")) { /*Si se envia una imagen obtiene la imagen para guardarla en el server luego*/ File img = new File(sel.getImagen()); /*Se ejecuta el metodo de registrar usuario que se encuentra, en la clase modelo con los datos que se encuentran en la clase*/ b = sel.setRegistrarSeleccion(sel.getNombre(), sel.getTipo(), sel.getTypeImg()); if (b) { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg()); img.renameTo(imagedb); session.setAttribute("Mensaje", "El gusto o ambiente ha sido registrado correctamente."); session.setAttribute("TipoMensaje", "Dio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } else { img.delete(); /*Se guarda un mensaje de error mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", sel.getMensaje()); session.setAttribute("TipoMensaje", "NODio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } } else { /*Se guarda un mensaje de error mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Seleccione una imagen, para registrar el ambiente o gusto."); session.setAttribute("TipoMensaje", "NODio"); } } else if (name.equals("ModificarSeleccion")) { if (sel.getImagen().equals("")) { /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo con los datos que se encuentran en la clase*/ b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(), sel.getEstado()); if (b) { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "El gusto o ambiente ha sido registrada correctamente."); session.setAttribute("TipoMensaje", "Dio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", sel.getMensaje()); session.setAttribute("TipoMensaje", "NODio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } } else { /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo con los datos que se encuentran en la clase*/ File img = new File(sel.getImagen()); b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(), sel.getTypeImg(), sel.getEstado()); if (b) { File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg()); img.renameTo(imagedb); /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "El gusto o ambiente ha sido modificado correctamente."); session.setAttribute("TipoMensaje", "Dio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } else { img.delete(); /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", sel.getMensaje()); session.setAttribute("TipoMensaje", "NODio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } } } } else { if (!item.getName().equals("")) { //uploaded files will come here. FileItem file = item; String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (sizeInBytes > 1000000) { /*Se muestra un mensaje en caso de pesar mas de 3 MB*/ session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB"); session.setAttribute("TipoMensaje", "NODio"); /*Se redirecciona*/ response.sendRedirect("View/ConsultaSeleccion.jsp"); } else { if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) { if (contentType.indexOf("jpeg") > 0) { contentType = ".jpg"; } else { contentType = ".png"; } /*Se crea la imagne*/ File archivo_server = new File(urlimgservidor + "/" + item.getName()); /*Se guardael nombre y tipo de imagen en la clase*/ sel.setImagen(urlimgservidor + "/" + item.getName()); sel.setTypeImg(contentType); /*Se guarda la imagen*/ item.write(archivo_server); } else { session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG"); session.setAttribute("TipoMensaje", "NODio"); } } } else { /*Se guarda el url de la imagen en la clase*/ sel.setImagen(""); } } } /*Se redirecciona sino se recive ninguna peticion*/ response.sendRedirect("View/index.jsp"); } catch (FileUploadException ex) { /*Se muestra un mensaje en caso de error*/ System.out.print(ex.getMessage().toString()); } catch (Exception ex) { /*Se muestra un mensaje en caso de error*/ Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:fr.paris.lutece.plugins.calendar.web.CalendarJspBean.java
/** * Process Event creation//ww w . j a va2s.c o m * * @param request The Http request * @return URL */ public String doCreateEvent(HttpServletRequest request) { String strJspReturn = StringUtils.EMPTY; String strCalendarId = request.getParameter(Constants.PARAMETER_CALENDAR_ID); String strPeriodicity = request.getParameter(Constants.PARAMETER_PERIODICITY); if (StringUtils.isNotBlank(strCalendarId) && StringUtils.isNumeric(strCalendarId) && StringUtils.isNotBlank(strPeriodicity) && StringUtils.isNumeric(strPeriodicity)) { //Retrieving parameters from form int nCalendarId = Integer.parseInt(strCalendarId); int nPeriodicity = Integer.parseInt(strPeriodicity); String strEventDateEnd = request.getParameter(Constants.PARAMETER_EVENT_DATE_END); String strTimeStart = request.getParameter(Constants.PARAMETER_EVENT_TIME_START); String strTimeEnd = request.getParameter(Constants.PARAMETER_EVENT_TIME_END); String strOccurrence = request.getParameter(Constants.PARAMETER_OCCURRENCE); String strEventTitle = request.getParameter(Constants.PARAMETER_EVENT_TITLE); String strDate = request.getParameter(Constants.PARAMETER_EVENT_DATE); String strNotify = request.getParameter(Constants.PARAMETER_NOTIFY); //Retrieve the features of an event from form String strDescription = request.getParameter(Constants.PARAMETER_DESCRIPTION); String strEventTags = request.getParameter(Constants.PARAMETER_EVENT_TAGS).trim(); String strLocationAddress = request.getParameter(Constants.PARAMETER_EVENT_LOCATION_ADDRESS).trim(); String strLocationTown = request.getParameter(Constants.PARAMETER_LOCATION_TOWN).trim(); String strLocation = request.getParameter(Constants.PARAMETER_LOCATION).trim(); String strLocationZip = request.getParameter(Constants.PARAMETER_LOCATION_ZIP).trim(); String strLinkUrl = request.getParameter(Constants.PARAMETER_EVENT_LINK_URL).trim(); String strDocumentId = request.getParameter(Constants.PARAMETER_EVENT_DOCUMENT_ID).trim(); String strPageUrl = request.getParameter(Constants.PARAMETER_EVENT_PAGE_URL).trim(); String strTopEvent = request.getParameter(Constants.PARAMETER_EVENT_TOP_EVENT).trim(); String strMapUrl = request.getParameter(Constants.PARAMETER_EVENT_MAP_URL).trim(); //Retrieving the excluded days String[] arrayExcludedDays = request.getParameterValues(Constants.PARAMETER_EXCLUDED_DAYS); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; FileItem item = mRequest.getFile(Constants.PARAMETER_EVENT_IMAGE); String[] arrayCategory = request.getParameterValues(Constants.PARAMETER_CATEGORY); //Categories List<Category> listCategories = new ArrayList<Category>(); if (arrayCategory != null) { for (String strIdCategory : arrayCategory) { Category category = CategoryHome.find(Integer.parseInt(strIdCategory), getPlugin()); if (category != null) { listCategories.add(category); } } } String[] strTabEventTags = null; // Mandatory field if (StringUtils.isBlank(strDate) || StringUtils.isBlank(strEventTitle) || StringUtils.isBlank(strDescription)) { return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } if (StringUtils.isNotBlank(strEventTags) && strEventTags.length() > 0) { //Test if there aren't special characters in tag list boolean isAllowedExp = Pattern.matches(PROPERTY_TAGS_REGEXP, strEventTags); if (!isAllowedExp) { return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_TAG, AdminMessage.TYPE_STOP); } strTabEventTags = strEventTags.split("\\s"); } //Convert the date in form to a java.util.Date object Date dateEvent = DateUtil.formatDate(strDate, getLocale()); if ((dateEvent == null) || !Utils.isValidDate(dateEvent)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT, AdminMessage.TYPE_STOP); } Date dateEndEvent = null; if (StringUtils.isNotBlank(strEventDateEnd)) { dateEndEvent = DateUtil.formatDate(strEventDateEnd, getLocale()); if ((dateEndEvent == null) || !Utils.isValidDate(dateEndEvent)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT, AdminMessage.TYPE_STOP); } } //the number of occurrence is 1 by default int nOccurrence = 1; if ((strOccurrence.length() > 0) && !strOccurrence.equals("")) { try { nOccurrence = Integer.parseInt(strOccurrence); } catch (NumberFormatException e) { return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_OCCURRENCE_NUMBER, AdminMessage.TYPE_STOP); } } int nDocumentId = -1; if ((strDocumentId.length() > 0) && !strDocumentId.equals("")) { try { nDocumentId = Integer.parseInt(strDocumentId); } catch (NumberFormatException e) { return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_OCCURRENCE_NUMBER, AdminMessage.TYPE_STOP); } } if (!Utils.checkTime(strTimeStart) || !Utils.checkTime(strTimeEnd)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_TIMEFORMAT, AdminMessage.TYPE_STOP); } //If a date end is chosen if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 1) && StringUtils.isNotBlank(strEventDateEnd)) { if (dateEndEvent.before(dateEvent)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATE_END_BEFORE, AdminMessage.TYPE_STOP); } nPeriodicity = 0; nOccurrence = Utils.getOccurrenceWithinTwoDates(dateEvent, dateEndEvent, arrayExcludedDays); } else if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 1) && StringUtils.isBlank(strEventDateEnd)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT, AdminMessage.TYPE_STOP); } //If a date end is not chosen if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 0) && StringUtils.isBlank(strEventDateEnd)) { dateEndEvent = Utils.getDateForward(dateEvent, nPeriodicity, nOccurrence, arrayExcludedDays); if (dateEndEvent.before(dateEvent)) { nOccurrence = 0; dateEndEvent = dateEvent; } } SimpleEvent event = new SimpleEvent(); event.setDate(dateEvent); event.setDateEnd(dateEndEvent); event.setDateTimeStart(strTimeStart); event.setDateTimeEnd(strTimeEnd); event.setTitle(strEventTitle); event.setOccurrence(nOccurrence); event.setPeriodicity(nPeriodicity); event.setDescription(strDescription); if (item.getSize() == 0) { HttpSession session = request.getSession(true); if (session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE) != null && session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE) != null) { ImageResource imageResource = new ImageResource(); imageResource.setImage( (byte[]) session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE)); imageResource.setMimeType( (String) session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE)); event.setImageResource(imageResource); session.removeAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE); session.removeAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE); } } if (item.getSize() >= 1) { ImageResource imageResource = new ImageResource(); imageResource.setImage(item.get()); imageResource.setMimeType(item.getContentType()); event.setImageResource(imageResource); } event.setTags(strTabEventTags); event.setLocationAddress(strLocationAddress); event.setLocation(strLocation); event.setLocationTown(strLocationTown); event.setLocationZip(strLocationZip); event.setLinkUrl(strLinkUrl); event.setPageUrl(strPageUrl); event.setTopEvent(Integer.parseInt(strTopEvent)); event.setMapUrl(strMapUrl); event.setDocumentId(nDocumentId); event.setListCategories(listCategories); event.setExcludedDays(arrayExcludedDays); event.setIdCalendar(nCalendarId); _eventListService.doAddEvent(event, null, getPlugin()); List<OccurrenceEvent> listOccurencesEvent = _eventListService.getOccurrenceEvents(nCalendarId, event.getId(), Constants.SORT_ASC, getPlugin()); for (OccurrenceEvent occ : listOccurencesEvent) { IndexationService.addIndexerAction(Integer.toString(occ.getId()), AppPropertiesService.getProperty(CalendarIndexer.PROPERTY_INDEXER_NAME), IndexerAction.TASK_CREATE); CalendarIndexerUtils.addIndexerAction(occ.getId(), IndexerAction.TASK_CREATE); } /* * IndexationService.addIndexerAction( Constants.EMPTY_STRING + * nCalendarId * ,AppPropertiesService.getProperty( * CalendarIndexer.PROPERTY_INDEXER_NAME ), * IndexerAction.TASK_CREATE ); */ boolean isNotify = Boolean.parseBoolean(strNotify); if (isNotify) { int nSubscriber = _agendaSubscriberService.getSubscriberNumber(nCalendarId, getPlugin()); if (nSubscriber > 0) { Collection<CalendarSubscriber> calendarSubscribers = _agendaSubscriberService .getSubscribers(nCalendarId, getPlugin()); _agendaSubscriberService.sendSubscriberMail(request, calendarSubscribers, event, nCalendarId); } } strJspReturn = AppPathService.getBaseUrl(request) + JSP_EVENT_LIST2 + nCalendarId; } else { strJspReturn = AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_NUMBER_FORMAT, AdminMessage.TYPE_STOP); } return strJspReturn; }
From source file:com.intbit.ServletModel.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w .ja va2s . co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { look = new Looks(); // uploadXmlPath = getServletContext().getRealPath("") + "/model"; uploadPath = AppConstants.BASE_MODEL_PATH; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); if (fieldName.equals("organization")) { lookName = fi.getString(); } if (fieldName.equals("users")) { lookName = fi.getString(); } if (fieldName.equals("categories")) { lookName = fi.getString(); } if (fieldName.equals("mapper")) { lookName = fi.getString(); } if (fieldName.equals("layout")) { lookName = fi.getString(); } if (fieldName.equals("mail")) { lookName = fi.getString(); } if (fieldName.equals("socialmedia")) { lookName = fi.getString(); } if (fieldName.equals("textstyle")) { lookName = fi.getString(); } if (fieldName.equals("containerstyle")) { lookName = fi.getString(); } if (fieldName.equals("element")) { lookName = fi.getString(); } String textstyleinfo = request.getParameter("textstyle"); String containerstyle = request.getParameter("containerstyle"); String mapfiledata = request.getParameter("element"); String textstylearray[] = textstyleinfo.split(","); String containerstylearray[] = containerstyle.split(" "); String mapfiledataarray[] = mapfiledata.split(","); // String image = request.getParameter("image"); logger.log(Level.INFO, containerstyle); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("layout"); doc.appendChild(rootElement); Document doc1 = docBuilder.newDocument(); Element rootElement1 = doc1.createElement("models"); doc1.appendChild(rootElement1); Element container = doc.createElement("container"); rootElement.appendChild(container); // for (int i = 0; i <= containerstylearray.length - 1; i++) { // String v[] = containerstylearray[i].split(":"); // Attr attr = doc.createAttribute(v[0]); // attr.setValue("" + v[1]); // container.setAttributeNode(attr); // } // // // staff elements // for (int i = 0; i <= textstylearray.length - 1; i++) { // Element element = doc.createElement("element"); // rootElement.appendChild(element); // String field1[] = textstylearray[i].split(" "); // for (int j = 0; j <= field1.length - 1; j++) { // String field2[] = field1[j].split(":"); // for (int k = 0; k < field2.length - 1; k++) { // Attr attr = doc.createAttribute(field2[0]); // attr.setValue("" + field2[1]); // element.setAttributeNode(attr); // } // } // } // // // for mapper xml file // for (int i = 0; i <= mapfiledataarray.length - 1; i++) { // Element element1 = doc1.createElement("model"); // rootElement1.appendChild(element1); // String field1[] = mapfiledataarray[i].split(" "); // for (int j = 0; j <= field1.length - 1; j++) { // String field2[] = field1[j].split(":"); // for (int k = 0; k < field2.length - 1; k++) { // Attr attr = doc1.createAttribute(field2[k]); // attr.setValue("" + field2[1]); // element1.setAttributeNode(attr); // } // } // } // write the content into xml file // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(new File(uploadPath +File.separator + layoutfilename + ".xml")); // // TransformerFactory transformerFactory1 = TransformerFactory.newInstance(); // Transformer transformer1 = transformerFactory1.newTransformer(); // DOMSource source1 = new DOMSource(doc1); // StreamResult result1 = new StreamResult(new File(uploadPath +File.separator + mapperfilename + ".xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); // transformer.transform(source, result); // transformer1.transform(source1, result1); // layout.addLayouts(organization_id , user_id, category_id, layoutfilename, mapperfilename, type_email, type_social); } else { fieldName = fi.getFieldName(); fileName = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } int inStr = fileName.indexOf("."); String Str = fileName.substring(0, inStr); fileName = lookName + "_" + Str + ".png"; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } // look.addLooks(lookName, fileName); response.sendRedirect(request.getContextPath() + "/admin/looks.jsp"); // request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp"); // request_dispatcher.forward(request, response); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:", getSqlMethodsInstance().error)); out.println(getSqlMethodsInstance().error); } finally { out.close(); } }
From source file:com.occamlab.te.web.TestServlet.java
public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {//from ww w . jav a 2 s .c o m FileItemFactory ffactory; ServletFileUpload upload; List /* FileItem */ items = null; HashMap<String, String> params = new HashMap<String, String>(); boolean multipart = ServletFileUpload.isMultipartContent(request); if (multipart) { ffactory = new DiskFileItemFactory(); upload = new ServletFileUpload(ffactory); items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } } } else { Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String name = (String) paramNames.nextElement(); params.put(name, request.getParameter(name)); } } HttpSession session = request.getSession(); ServletOutputStream out = response.getOutputStream(); String operation = params.get("te-operation"); if (operation.equals("Test")) { TestSession s = new TestSession(); String user = request.getRemoteUser(); File logdir = new File(conf.getUsersDir(), user); String mode = params.get("mode"); RuntimeOptions opts = new RuntimeOptions(); opts.setWorkDir(conf.getWorkDir()); opts.setLogDir(logdir); if (mode.equals("retest")) { opts.setMode(Test.RETEST_MODE); String sessionid = params.get("session"); String test = params.get("test"); if (sessionid == null) { int i = test.indexOf("/"); sessionid = i > 0 ? test.substring(0, i) : test; } opts.setSessionId(sessionid); if (test == null) { opts.addTestPath(sessionid); } else { opts.addTestPath(test); } for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { String profileId = entry.getValue(); int i = profileId.indexOf("}"); opts.addTestPath(sessionid + "/" + profileId.substring(i + 1)); } } s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else if (mode.equals("resume")) { opts.setMode(Test.RESUME_MODE); String sessionid = params.get("session"); opts.setSessionId(sessionid); s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else { opts.setMode(Test.TEST_MODE); String sessionid = LogUtils.generateSessionId(logdir); s.setSessionId(sessionid); String sources = params.get("sources"); s.setSourcesName(sources); SuiteEntry suite = conf.getSuites().get(sources); s.setSuiteName(suite.getId()); // String suite = params.get("suite"); // s.setSuiteName(suite); String description = params.get("description"); s.setDescription(description); opts.setSessionId(sessionid); opts.setSourcesName(sources); opts.setSuiteName(suite.getId()); ArrayList<String> profiles = new ArrayList<String>(); for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { profiles.add(entry.getValue()); opts.addProfile(entry.getValue()); } } s.setProfiles(profiles); s.save(logdir); } String webdir = conf.getWebDirs().get(s.getSourcesName()); // String requestURI = request.getRequestURI(); // String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1); // URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null); URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), request.getRequestURI(), null, null); opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString()); // URI baseURI = new URL(contextURI.toURL(), webdir).toURI(); // String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/"; // opts.setBaseURI(base); //System.out.println(opts.getSourcesName()); TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts); //System.out.println(indexes.get(opts.getSourcesName()).toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); core.setOut(ps); core.setWeb(true); Thread thread = new Thread(core); session.setAttribute("testsession", core); thread.start(); response.setContentType("text/xml"); out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>"); } else if (operation.equals("Stop")) { response.setContentType("text/xml"); TECore core = (TECore) session.getAttribute("testsession"); if (core != null) { core.stopThread(); session.removeAttribute("testsession"); out.println("<stopped/>"); } else { out.println("<message>Could not retrieve core object</message>"); } } else if (operation.equals("GetStatus")) { TECore core = (TECore) session.getAttribute("testsession"); response.setContentType("text/xml"); out.print("<status"); if (core.getFormHtml() != null) { out.print(" form=\"true\""); } if (core.isThreadComplete()) { out.print(" complete=\"true\""); session.removeAttribute("testsession"); } out.println(">"); out.print("<![CDATA["); // out.print(core.getOutput()); out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' ')); out.println("]]>"); out.println("</status>"); } else if (operation.equals("GetForm")) { TECore core = (TECore) session.getAttribute("testsession"); String html = core.getFormHtml(); core.setFormHtml(null); response.setContentType("text/html"); out.print(html); } else if (operation.equals("SubmitForm")) { TECore core = (TECore) session.getAttribute("testsession"); Document doc = DB.newDocument(); Element root = doc.createElement("values"); doc.appendChild(root); for (String key : params.keySet()) { if (!key.startsWith("te-")) { Element valueElement = doc.createElement("value"); valueElement.setAttribute("key", key); valueElement.appendChild(doc.createTextNode(params.get(key))); root.appendChild(valueElement); } } if (multipart) { Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField() && !item.getName().equals("")) { File uploadedFile = new File(core.getLogDir(), StringUtils.getFilenameFromString(item.getName())); item.write(uploadedFile); Element valueElement = doc.createElement("value"); String key = item.getFieldName(); valueElement.setAttribute("key", key); if (core.getFormParsers().containsKey(key)) { Element parser = core.getFormParsers().get(key); URL url = uploadedFile.toURI().toURL(); Element resp = core.parse(url.openConnection(), parser, doc); Element content = DomUtils.getElementByTagName(resp, "content"); if (content != null) { Element child = DomUtils.getChildElement(content); if (child != null) { valueElement.appendChild(child); } } } else { Element fileEntry = doc.createElementNS(CTL_NS, "file-entry"); fileEntry.setAttribute("full-path", uploadedFile.getAbsolutePath().replace('\\', '/')); fileEntry.setAttribute("media-type", item.getContentType()); fileEntry.setAttribute("size", String.valueOf(item.getSize())); valueElement.appendChild(fileEntry); } root.appendChild(valueElement); } } } core.setFormResults(doc); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>Form Submitted</title></head>"); out.print("<body onload=\"window.parent.update()\"></body>"); out.println("</html>"); } } catch (Throwable t) { throw new ServletException(t); } }
From source file:com.tmwsoft.sns.web.action.MainAction.java
public ActionForward cp_topic(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> sGlobal = (Map<String, Object>) request.getAttribute("sGlobal"); Map<String, Object> sConfig = (Map<String, Object>) request.getAttribute("sConfig"); Map<String, Object> space = (Map<String, Object>) request.getAttribute("space"); int supe_uid = (Integer) sGlobal.get("supe_uid"); int timestamp = (Integer) sGlobal.get("timestamp"); String tempS = request.getParameter("topicid"); int topicid = Common.empty(tempS) ? 0 : Common.intval(tempS); tempS = request.getParameter("id"); int id = Common.empty(tempS) ? 0 : Common.intval(tempS); tempS = request.getParameter("idtype"); String idtype = Common.empty(tempS) ? "" : tempS.trim(); tempS = request.getParameter("op"); String op = Common.empty(tempS) ? "" : tempS; List<Map<String, Object>> query; Map<String, Object> topic = null; if (topicid != 0) { query = dataBaseService.executeQuery("SELECT * FROM sns_topic WHERE topicid='" + topicid + "'"); topic = query.size() > 0 ? query.get(0) : null; }/*from ww w .ja va2 s. c o m*/ if (Common.empty(topic)) { if (!"join".equals(op)) { if (!Common.checkPerm(request, response, "allowtopic")) { Common.ckSpaceLog(request); return showMessage(request, response, "no_privilege"); } } topicid = 0; } else { if (!"join".equals(op)) { if (supe_uid != (Integer) topic.get("uid") && !Common.checkPerm(request, response, "managetopic")) { return showMessage(request, response, "no_privilege"); } } topic.put("pic", Common.pic_get(sConfig, (String) topic.get("pic"), (Integer) topic.get("thumb"), (Integer) topic.get("remote"), true)); } boolean sc; FileUploadUtil upload = getParsedFileUploadUtil(request); try { sc = submitCheckForMulti(request, upload, "topicsubmit"); } catch (Exception e) { e.printStackTrace(); return showMessage(request, response, e.getMessage()); } if (sc) { Map<String, Object> setarr = new HashMap<String, Object>(); String subject; String message; try { subject = Common.getStr(upload.getParameter("subject"), 80, true, true, false, 0, 0, request, response); message = Common.getStr(upload.getParameter("message"), 0, true, true, false, 0, 0, request, response); } catch (Exception e) { return showMessage(request, response, e.getMessage()); } setarr.put("subject", subject); setarr.put("message", message); String[] tempSA = upload.getParameterValues("jointype[]"); setarr.put("jointype", Common.empty(tempSA) ? "" : Common.implode(tempSA, ",")); tempSA = upload.getParameterValues("joingid[]"); setarr.put("joingid", Common.empty(tempSA) ? "" : Common.implode(tempSA, ",")); tempS = upload.getParameter("endtime"); setarr.put("endtime", Common.empty(tempS) ? 0 : Common.strToTime(tempS, Common.getTimeOffset(sGlobal, sConfig), "yyyy-MM-dd HH:mm")); if (Common.strlen(subject) < 4) { return showMessage(request, response, "topic_subject_error"); } FileItem fileItem = upload.getFileItem("pic"); if (fileItem != null && fileItem.getSize() > 0) { Object ob = mainService.savePic(request, response, fileItem, "-1", "", 0); if (!Common.empty(ob) && Common.isArray(ob)) { Map<String, Object> filearr = (Map<String, Object>) ob; setarr.put("pic", filearr.get("filepath")); setarr.put("thumb", filearr.get("thumb")); setarr.put("remote", filearr.get("remote")); } } if (Common.empty(topicid)) { setarr.put("uid", supe_uid); setarr.put("username", sGlobal.get("supe_username")); setarr.put("dateline", timestamp); setarr.put("lastpost", timestamp); topicid = dataBaseService.insertTable("sns_topic", setarr, true, false); } else { Map<String, Object> whereData = new HashMap<String, Object>(); whereData.put("topicid", topicid); dataBaseService.updateTable("sns_topic", setarr, whereData); } return showMessage(request, response, "do_success", "zone.action?do=topic&topicid=" + topicid, 0); } if ("delete".equals(op)) { try { if (submitCheck(request, "deletesubmit")) { if (adminDeleteService.deletetopics(request, response, sGlobal, topicid)) { return showMessage(request, response, "do_success", "zone.action?do=topic"); } else { return showMessage(request, response, "failed_to_delete_operation"); } } } catch (Exception e) { return showMessage(request, response, e.getMessage()); } request.setAttribute("topicid", topicid); } else if ("join".equals(op)) { String tablename = mainService.getTablebyIdType(idtype); Map<String, Object> item = null; if (!Common.empty(tablename) && id != 0) { if (tablename.equals("pic")) { query = dataBaseService.executeQuery( "SELECT s.username, p.* FROM sns_pic p LEFT JOIN sns_space s ON s.uid=p.uid WHERE p.picid='" + id + "'"); } else { query = dataBaseService .executeQuery("SELECT * FROM " + tablename + " WHERE " + idtype + "='" + id + "'"); } item = query.size() > 0 ? query.get(0) : null; } if (Common.empty(item)) { return showMessage(request, response, "no_privilege"); } int uid = (Integer) item.get("uid"); if (supe_uid != uid && !Common.checkPerm(request, response, "managetopic") && !Common.checkPerm(request, response, tablename.replace("sns_", "manage"))) { return showMessage(request, response, "no_privilege"); } Map<Integer, Map<String, Object>> tlist = new LinkedHashMap<Integer, Map<String, Object>>(); query = dataBaseService.executeQuery("SELECT * FROM sns_topic ORDER BY lastpost DESC LIMIT 0,50"); String[] jointype; String[] joingid; Integer endtime; for (Map<String, Object> value : query) { tempS = (String) value.get("jointype"); if (!Common.empty(tempS)) { jointype = tempS.split(","); } else { jointype = null; } if (!Common.empty(jointype) && !Common.in_array(jointype, tablename)) { continue; } if (supe_uid == uid) { tempS = (String) value.get("joingid"); if (!Common.empty(tempS)) { joingid = tempS.split(","); } else { joingid = null; } if (!Common.empty(joingid) && !Common.in_array(joingid, space.get("groupid"))) { continue; } } endtime = (Integer) value.get("endtime"); if (endtime != 0 && timestamp > endtime) { continue; } tlist.put((Integer) value.get("topicid"), value); } if (Common.empty(tlist)) { return showMessage(request, response, "topic_list_none"); } try { if (submitCheck(request, "joinsubmit")) { int newtopicid = Common.intval(request.getParameter("newtopicid")); if (Common.empty(tlist.get(newtopicid))) { newtopicid = 0; } Map<String, Object> setData = new HashMap<String, Object>(); setData.put("topicid", newtopicid); Map<String, Object> whereData = new HashMap<String, Object>(); whereData.put(idtype, id); dataBaseService.updateTable(tablename, setData, whereData); if (newtopicid != 0) { mainService.topicJoin(request, newtopicid, uid, Common.addSlashes((String) item.get("username"))); } else { query = dataBaseService.executeQuery("SELECT * FROM sns_topicuser WHERE uid='" + uid + "' AND topicid='" + item.get("topicid") + "'"); Map<String, Object> value = query.size() > 0 ? query.get(0) : null; if (!Common.empty(value)) { dataBaseService.execute("DELETE FROM sns_topicuser WHERE id='" + value.get("id") + "'"); dataBaseService.executeUpdate("UPDATE sns_topic SET joinnum=joinnum-1 WHERE topicid='" + item.get("topicid") + "' AND joinnum>0"); } } return showMessage(request, response, "do_success", request.getParameter("refer"), 0); } } catch (Exception e) { return showMessage(request, response, e.getMessage()); } request.setAttribute("id", id); request.setAttribute("idtype", idtype); request.setAttribute("tlist", tlist); } else if ("ignore".equals(op)) { request.setAttribute("topicid", topicid); request.setAttribute("id", id); request.setAttribute("idtype", idtype); } else { if (topic == null) { topic = new HashMap<String, Object>(); } Map<String, String> jointypes = new HashMap<String, String>(); tempS = (String) topic.get("jointype"); String[] tempSA = null; if (tempS != null) { tempSA = tempS.split(","); } topic.put("jointype", tempSA); if (tempSA != null) { for (String value : tempSA) { jointypes.put(value, " checked"); } } Map<String, String> joingids = new HashMap<String, String>(); tempS = (String) topic.get("joingid"); tempSA = null; if (tempS != null) { tempSA = tempS.split(","); } topic.put("joingid", tempSA); if (tempSA != null) { for (String value : tempSA) { joingids.put(value, " checked"); } } Object endtimeO = topic.get("endtime"); if (!Common.empty(endtimeO)) { topic.put("endtime", Common.sgmdate(request, "yyyy-MM-dd HH:mm", (Integer) endtimeO)); } else { topic.put("endtime", ""); } Map<Integer, Map<String, Map<String, Object>>> usergroups = new LinkedHashMap<Integer, Map<String, Map<String, Object>>>(); usergroups.put(-1, new LinkedHashMap<String, Map<String, Object>>()); usergroups.put(1, new LinkedHashMap<String, Map<String, Object>>()); usergroups.put(0, new LinkedHashMap<String, Map<String, Object>>()); query = dataBaseService.executeQuery("SELECT * FROM sns_usergroup"); Map<String, Map<String, Object>> tempM; for (Map<String, Object> value : query) { tempM = usergroups.get((Integer) value.get("system")); if (tempM != null) { tempM.put(String.valueOf(value.get("gid")), value); } } request.setAttribute("topicid", topicid); request.setAttribute("topic", topic); request.setAttribute("jointypes", jointypes); request.setAttribute("joingids", joingids); request.setAttribute("usergroups", usergroups); } request.setAttribute("op", op); return include(request, response, sConfig, sGlobal, "cp_topic.jsp"); }
From source file:cn.jcenterhome.web.action.CpAction.java
public ActionForward cp_topic(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> sGlobal = (Map<String, Object>) request.getAttribute("sGlobal"); Map<String, Object> sConfig = (Map<String, Object>) request.getAttribute("sConfig"); Map<String, Object> space = (Map<String, Object>) request.getAttribute("space"); int supe_uid = (Integer) sGlobal.get("supe_uid"); int timestamp = (Integer) sGlobal.get("timestamp"); String tempS = request.getParameter("topicid"); int topicid = Common.empty(tempS) ? 0 : Common.intval(tempS); tempS = request.getParameter("id"); int id = Common.empty(tempS) ? 0 : Common.intval(tempS); tempS = request.getParameter("idtype"); String idtype = Common.empty(tempS) ? "" : tempS.trim(); tempS = request.getParameter("op"); String op = Common.empty(tempS) ? "" : tempS; List<Map<String, Object>> query; Map<String, Object> topic = null; if (topicid != 0) { query = dataBaseService.executeQuery( "SELECT * FROM " + JavaCenterHome.getTableName("topic") + " WHERE topicid='" + topicid + "'"); topic = query.size() > 0 ? query.get(0) : null; }//from w w w . ja v a2s . c o m if (Common.empty(topic)) { if (!"join".equals(op)) { if (!Common.checkPerm(request, response, "allowtopic")) { Common.ckSpaceLog(request); return showMessage(request, response, "no_privilege"); } } topicid = 0; } else { if (!"join".equals(op)) { if (supe_uid != (Integer) topic.get("uid") && !Common.checkPerm(request, response, "managetopic")) { return showMessage(request, response, "no_privilege"); } } topic.put("pic", Common.pic_get(sConfig, (String) topic.get("pic"), (Integer) topic.get("thumb"), (Integer) topic.get("remote"), true)); } boolean sc; FileUploadUtil upload = getParsedFileUploadUtil(request); try { sc = submitCheckForMulti(request, upload, "topicsubmit"); } catch (Exception e) { e.printStackTrace(); return showMessage(request, response, e.getMessage()); } if (sc) { Map<String, Object> setarr = new HashMap<String, Object>(); String subject; String message; try { subject = Common.getStr(upload.getParameter("subject"), 80, true, true, false, 0, 0, request, response); message = Common.getStr(upload.getParameter("message"), 0, true, true, false, 0, 0, request, response); } catch (Exception e) { return showMessage(request, response, e.getMessage()); } setarr.put("subject", subject); setarr.put("message", message); String[] tempSA = upload.getParameterValues("jointype[]"); setarr.put("jointype", Common.empty(tempSA) ? "" : Common.implode(tempSA, ",")); tempSA = upload.getParameterValues("joingid[]"); setarr.put("joingid", Common.empty(tempSA) ? "" : Common.implode(tempSA, ",")); tempS = upload.getParameter("endtime"); setarr.put("endtime", Common.empty(tempS) ? 0 : Common.strToTime(tempS, Common.getTimeOffset(sGlobal, sConfig), "yyyy-MM-dd HH:mm")); if (Common.strlen(subject) < 4) { return showMessage(request, response, "topic_subject_error"); } FileItem fileItem = upload.getFileItem("pic"); if (fileItem != null && fileItem.getSize() > 0) { Object ob = cpService.savePic(request, response, fileItem, "-1", "", 0); if (!Common.empty(ob) && Common.isArray(ob)) { Map<String, Object> filearr = (Map<String, Object>) ob; setarr.put("pic", filearr.get("filepath")); setarr.put("thumb", filearr.get("thumb")); setarr.put("remote", filearr.get("remote")); } } if (Common.empty(topicid)) { setarr.put("uid", supe_uid); setarr.put("username", sGlobal.get("supe_username")); setarr.put("dateline", timestamp); setarr.put("lastpost", timestamp); topicid = dataBaseService.insertTable("topic", setarr, true, false); } else { Map<String, Object> whereData = new HashMap<String, Object>(); whereData.put("topicid", topicid); dataBaseService.updateTable("topic", setarr, whereData); } return showMessage(request, response, "do_success", "space.jsp?do=topic&topicid=" + topicid, 0); } if ("delete".equals(op)) { try { if (submitCheck(request, "deletesubmit")) { if (adminDeleteService.deletetopics(request, response, sGlobal, topicid)) { return showMessage(request, response, "do_success", "space.jsp?do=topic"); } else { return showMessage(request, response, "failed_to_delete_operation"); } } } catch (Exception e) { return showMessage(request, response, e.getMessage()); } request.setAttribute("topicid", topicid); } else if ("join".equals(op)) { String tablename = cpService.getTablebyIdType(idtype); Map<String, Object> item = null; if (!Common.empty(tablename) && id != 0) { if (tablename.equals("pic")) { query = dataBaseService .executeQuery("SELECT s.username, p.* FROM " + JavaCenterHome.getTableName("pic") + " p " + "LEFT JOIN " + JavaCenterHome.getTableName("space") + " s ON s.uid=p.uid " + "WHERE p.picid='" + id + "'"); } else { query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName(tablename) + " WHERE " + idtype + "='" + id + "'"); } item = query.size() > 0 ? query.get(0) : null; } if (Common.empty(item)) { return showMessage(request, response, "no_privilege"); } int uid = (Integer) item.get("uid"); if (supe_uid != uid && !Common.checkPerm(request, response, "managetopic") && !Common.checkPerm(request, response, "manage" + tablename)) { return showMessage(request, response, "no_privilege"); } Map<Integer, Map<String, Object>> tlist = new LinkedHashMap<Integer, Map<String, Object>>(); query = dataBaseService.executeQuery( "SELECT * FROM " + JavaCenterHome.getTableName("topic") + " ORDER BY lastpost DESC LIMIT 0,50"); String[] jointype; String[] joingid; Integer endtime; for (Map<String, Object> value : query) { tempS = (String) value.get("jointype"); if (!Common.empty(tempS)) { jointype = tempS.split(","); } else { jointype = null; } if (!Common.empty(jointype) && !Common.in_array(jointype, tablename)) { continue; } if (supe_uid == uid) { tempS = (String) value.get("joingid"); if (!Common.empty(tempS)) { joingid = tempS.split(","); } else { joingid = null; } if (!Common.empty(joingid) && !Common.in_array(joingid, space.get("groupid"))) { continue; } } endtime = (Integer) value.get("endtime"); if (endtime != 0 && timestamp > endtime) { continue; } tlist.put((Integer) value.get("topicid"), value); } if (Common.empty(tlist)) { return showMessage(request, response, "topic_list_none"); } try { if (submitCheck(request, "joinsubmit")) { int newtopicid = Common.intval(request.getParameter("newtopicid")); if (Common.empty(tlist.get(newtopicid))) { newtopicid = 0; } Map<String, Object> setData = new HashMap<String, Object>(); setData.put("topicid", newtopicid); Map<String, Object> whereData = new HashMap<String, Object>(); whereData.put(idtype, id); dataBaseService.updateTable(tablename, setData, whereData); if (newtopicid != 0) { cpService.topicJoin(request, newtopicid, uid, Common.addSlashes((String) item.get("username"))); } else { query = dataBaseService .executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("topicuser") + " WHERE uid='" + uid + "' AND topicid='" + item.get("topicid") + "'"); Map<String, Object> value = query.size() > 0 ? query.get(0) : null; if (!Common.empty(value)) { dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("topicuser") + " WHERE id='" + value.get("id") + "'"); dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("topic") + " SET joinnum=joinnum-1 WHERE topicid='" + item.get("topicid") + "' AND joinnum>0"); } } return showMessage(request, response, "do_success", request.getParameter("refer"), 0); } } catch (Exception e) { return showMessage(request, response, e.getMessage()); } request.setAttribute("id", id); request.setAttribute("idtype", idtype); request.setAttribute("tlist", tlist); } else if ("ignore".equals(op)) { request.setAttribute("topicid", topicid); request.setAttribute("id", id); request.setAttribute("idtype", idtype); } else { if (topic == null) { topic = new HashMap<String, Object>(); } Map<String, String> jointypes = new HashMap<String, String>(); tempS = (String) topic.get("jointype"); String[] tempSA = null; if (tempS != null) { tempSA = tempS.split(","); } topic.put("jointype", tempSA); if (tempSA != null) { for (String value : tempSA) { jointypes.put(value, " checked"); } } Map<String, String> joingids = new HashMap<String, String>(); tempS = (String) topic.get("joingid"); tempSA = null; if (tempS != null) { tempSA = tempS.split(","); } topic.put("joingid", tempSA); if (tempSA != null) { for (String value : tempSA) { joingids.put(value, " checked"); } } Object endtimeO = topic.get("endtime"); if (!Common.empty(endtimeO)) { topic.put("endtime", Common.sgmdate(request, "yyyy-MM-dd HH:mm", (Integer) endtimeO)); } else { topic.put("endtime", ""); } Map<Integer, Map<String, Map<String, Object>>> usergroups = new LinkedHashMap<Integer, Map<String, Map<String, Object>>>(); usergroups.put(-1, new LinkedHashMap<String, Map<String, Object>>()); usergroups.put(1, new LinkedHashMap<String, Map<String, Object>>()); usergroups.put(0, new LinkedHashMap<String, Map<String, Object>>()); query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("usergroup")); Map<String, Map<String, Object>> tempM; for (Map<String, Object> value : query) { tempM = usergroups.get((Integer) value.get("system")); if (tempM != null) { tempM.put(String.valueOf(value.get("gid")), value); } } request.setAttribute("topicid", topicid); request.setAttribute("topic", topic); request.setAttribute("jointypes", jointypes); request.setAttribute("joingids", joingids); request.setAttribute("usergroups", usergroups); } request.setAttribute("op", op); return include(request, response, sConfig, sGlobal, "cp_topic.jsp"); }