List of usage examples for javax.servlet RequestDispatcher forward
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;
From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.VclassRetryController.java
public void doPost(HttpServletRequest req, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) { return;/*w ww. j a v a2 s. c o m*/ } VitroRequest request = new VitroRequest(req); //create an EditProcessObject for this and put it in the session EditProcessObject epo = super.createEpo(request); /*for testing*/ VClass testMask = new VClass(); epo.setBeanClass(VClass.class); epo.setImplementationClass(VClass.class); epo.setBeanMask(testMask); String action = null; if (epo.getAction() == null) { action = "insert"; epo.setAction("insert"); } else { action = epo.getAction(); } WebappDaoFactory wadf = ModelAccess.on(getServletContext()).getWebappDaoFactory(); VClassDao vcwDao = wadf.getVClassDao(); epo.setDataAccessObject(vcwDao); VClassGroupDao cgDao = wadf.getVClassGroupDao(); OntologyDao oDao = wadf.getOntologyDao(); VClass vclassForEditing = null; if (!epo.getUseRecycledBean()) { if (request.getParameter("uri") != null) { try { vclassForEditing = (VClass) vcwDao.getVClassByURI(request.getParameter("uri")); action = "update"; epo.setAction("update"); } catch (NullPointerException e) { log.error("Need to implement 'record not found' error message."); } } else { vclassForEditing = new VClass(); if (request.getParameter("GroupId") != null) { vclassForEditing.setGroupURI(request.getParameter("GroupURI")); } } epo.setOriginalBean(vclassForEditing); } else { vclassForEditing = (VClass) epo.getNewBean(); } //make a simple mask for the class's id Object[] simpleMaskPair = new Object[2]; simpleMaskPair[0] = "URI"; simpleMaskPair[1] = vclassForEditing.getURI(); epo.getSimpleMask().add(simpleMaskPair); //validators List localNameValidatorList = new ArrayList(); localNameValidatorList.add(new XMLNameValidator()); epo.getValidatorMap().put("LocalName", localNameValidatorList); //set up any listeners List changeListenerList = new LinkedList(); if (request.getParameter("superclassUri") != null) { changeListenerList.add(new SubclassListener(request.getParameter("superclassUri"), request.getUnfilteredWebappDaoFactory())); } epo.setChangeListenerList(changeListenerList); //make a postinsert pageforwarder that will send us to a new class's fetch screen epo.setPostInsertPageForwarder(new VclassInsertPageForwarder()); //make a postdelete pageforwarder that will send us to the list of classes epo.setPostDeletePageForwarder(new UrlForwarder("showClassHierarchy")); //set the getMethod so we can retrieve a new bean after we've inserted it try { Class[] args = new Class[1]; args[0] = String.class; epo.setGetMethod(VClassDao.class.getDeclaredMethod("getVClassByURI", args)); } catch (NoSuchMethodException e) { log.error(this.getClass().getName() + " could not find the getVClassByURI method"); } HashMap<String, List<Option>> optionMap = new HashMap<String, List<Option>>(); try { VClassGroupDao vcgDao = request.getUnfilteredWebappDaoFactory().getVClassGroupDao(); List classGroupOptionList = FormUtils.makeOptionListFromBeans(vcgDao.getPublicGroupsWithVClasses(), "URI", "PublicName", vclassForEditing.getGroupURI(), null, (vclassForEditing.getGroupURI() != null && !(vclassForEditing.getGroupURI().equals("")))); classGroupOptionList.add(0, new Option("", "none", ("update".equals(action) && (vclassForEditing.getGroupURI() == null || vclassForEditing.getGroupURI().equals(""))))); optionMap.put("GroupURI", classGroupOptionList); } catch (Exception e) { log.error("unable to create GroupId option list"); } try { List namespaceIdList = (action.equals("insert")) ? FormUtils.makeOptionListFromBeans(oDao.getAllOntologies(), "URI", "Name", ((vclassForEditing.getNamespace() == null) ? "" : vclassForEditing.getNamespace()), null, false) : FormUtils.makeOptionListFromBeans(oDao.getAllOntologies(), "URI", "Name", ((vclassForEditing.getNamespace() == null) ? "" : vclassForEditing.getNamespace()), null, true); namespaceIdList.add(0, new Option(request.getUnfilteredWebappDaoFactory().getDefaultNamespace(), "default")); optionMap.put("Namespace", namespaceIdList); } catch (Exception e) { log.error(this.getClass().getName() + "unable to create Namespace option list"); } optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getDisplayOptionsList(vclassForEditing)); optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getUpdateOptionsList(vclassForEditing)); optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getPublishOptionsList(vclassForEditing)); FormObject foo = new FormObject(); foo.setErrorMap(epo.getErrMsgMap()); foo.setOptionLists(optionMap); epo.setFormObject(foo); request.setAttribute("formValue", foo.getValues()); FormUtils.populateFormFromBean(vclassForEditing, action, foo, epo.getBadValueMap()); RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp"); request.setAttribute("formJsp", "/templates/edit/specific/vclass_retry.jsp"); request.setAttribute("colspan", "4"); request.setAttribute("scripts", "/templates/edit/formBasic.js"); request.setAttribute("title", "Class Editing Form"); request.setAttribute("_action", action); request.setAttribute("unqualifiedClassName", "VClass"); setRequestAttributes(request, epo); try { rd.forward(request, response); } catch (Exception e) { log.error("VclassRetryController could not forward to view.", e); throw new RuntimeException(e); } }
From source file:com.alfaariss.oa.sso.web.profile.user.UserProfile.java
private void forwardToIndex(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Enum error, List<TGTEventError> warnings, boolean bShowAuthNButton, ISession session) throws OAException { try {/* w w w . j a va 2s .c om*/ if (bShowAuthNButton) { IRequestor requestor = _requestorPoolFactory.getRequestor(_sUserPageRequestorId); if (requestor == null || !requestor.isEnabled()) { bShowAuthNButton = false; } else { RequestorPool requestorPool = _requestorPoolFactory.getRequestorPool(_sUserPageRequestorId); if (requestorPool == null || !requestorPool.isEnabled()) { bShowAuthNButton = false; } } } if (session != null) { servletRequest.setAttribute(ISession.ID_NAME, session.getId()); } if (bShowAuthNButton) { servletRequest.setAttribute(JSP_AUTHN_ENABLED, bShowAuthNButton); } if (error != null) { servletRequest.setAttribute(UserException.USEREVENT_NAME, error); } if (warnings != null) { servletRequest.setAttribute(DetailedUserException.DETAILS_NAME, warnings); } //Show user info //Set server info as attribute servletRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer()); //Forward to page RequestDispatcher oDispatcher = servletRequest.getRequestDispatcher(_sJSPUserIndex); if (oDispatcher != null) oDispatcher.forward(servletRequest, servletResponse); else { _logger.fatal("Forward request not supported"); throw new OAException(SystemErrors.ERROR_INTERNAL); } } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error during jsp forward", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.PropertyEditController.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) { return;/*from w w w . java 2s . c o m*/ } final int NUM_COLS = 26; VitroRequest vreq = new VitroRequest(request); ObjectPropertyDao propDao = vreq.getUnfilteredWebappDaoFactory().getObjectPropertyDao(); ObjectPropertyDao propDaoLangNeut = vreq.getLanguageNeutralWebappDaoFactory().getObjectPropertyDao(); VClassDao vcDao = vreq.getLanguageNeutralWebappDaoFactory().getVClassDao(); VClassDao vcDaoWLang = vreq.getUnfilteredWebappDaoFactory().getVClassDao(); PropertyGroupDao pgDao = vreq.getUnfilteredWebappDaoFactory().getPropertyGroupDao(); ObjectProperty p = propDao.getObjectPropertyByURI(request.getParameter("uri")); ObjectProperty pLangNeut = propDaoLangNeut.getObjectPropertyByURI(request.getParameter("uri")); request.setAttribute("property", p); ArrayList<String> results = new ArrayList<String>(); results.add("property"); // column 1 results.add("parent property"); // column 2 results.add("property group"); // column 3 results.add("ontology"); // column 4 results.add("RDF local name"); // column 5 results.add("public display label"); // column 6 results.add("domain class"); // column 7 results.add("range class"); // column 8 results.add("transitive"); // column 9 results.add("symmetric"); // column 10 results.add("functional"); // column 11 results.add("inverse functional"); // column 12 results.add("public description"); // column 13 results.add("example"); // column 14 results.add("editor description"); // column 15 results.add("display level"); // column 16 results.add("update level"); // column 17 results.add("display tier"); // column 18 results.add("display limit"); // column 15 results.add("collate by subclass"); // column 19 results.add("custom entry form"); // column 20 results.add("select from existing"); // column 21 results.add("offer create new"); // column 22 results.add("sort direction"); // column 23 results.add("URI"); // column 24 results.add("publish level"); // column 25 results.add(p.getPickListName()); // column 1 String parentPropertyStr = ""; if (p.getParentURI() != null) { ObjectProperty parent = propDao.getObjectPropertyByURI(p.getParentURI()); if (parent != null && parent.getURI() != null) { try { parentPropertyStr = "<a href=\"propertyEdit?uri=" + URLEncoder.encode(parent.getURI(), "UTF-8") + "\">" + parent.getPickListName() + "</a>"; } catch (UnsupportedEncodingException e) { log.error(e, e); } } } results.add(parentPropertyStr); // column 2 if (p.getGroupURI() != null) { PropertyGroup pGroup = pgDao.getGroupByURI(p.getGroupURI()); if (pGroup != null) { results.add(pGroup.getName()); // column 3 } else { results.add("(unnamed group)"); // column 3 } } else { results.add("(unspecified)"); // column 3 } String ontologyName = null; if (p.getNamespace() != null) { Ontology ont = vreq.getUnfilteredWebappDaoFactory().getOntologyDao().getOntologyByURI(p.getNamespace()); if ((ont != null) && (ont.getName() != null)) { ontologyName = ont.getName(); } } results.add(ontologyName == null ? "(not identified)" : ontologyName); // column 4 results.add(p.getLocalName()); // column 5 results.add(p.getDomainPublic() == null ? "(no public label)" : p.getDomainPublic()); // column 6 String domainStr = ""; if (pLangNeut.getDomainVClassURI() != null) { VClass domainClass = vcDao.getVClassByURI(pLangNeut.getDomainVClassURI()); VClass domainWLang = vcDaoWLang.getVClassByURI(pLangNeut.getDomainVClassURI()); if (domainClass != null && domainClass.getURI() != null && domainClass.getPickListName() != null) { try { if (domainClass.isAnonymous()) { domainStr = domainClass.getPickListName(); } else { domainStr = "<a href=\"vclassEdit?uri=" + URLEncoder.encode(domainClass.getURI(), "UTF-8") + "\">" + domainWLang.getPickListName() + "</a>"; } } catch (UnsupportedEncodingException e) { log.error(e, e); } } } results.add(domainStr); // column 7 String rangeStr = ""; if (pLangNeut.getRangeVClassURI() != null) { VClass rangeClass = vcDao.getVClassByURI(pLangNeut.getRangeVClassURI()); VClass rangeWLang = vcDaoWLang.getVClassByURI(pLangNeut.getRangeVClassURI()); if (rangeClass != null && rangeClass.getURI() != null && rangeClass.getPickListName() != null) { try { if (rangeClass.isAnonymous()) { rangeStr = rangeClass.getPickListName(); } else { rangeStr = "<a href=\"vclassEdit?uri=" + URLEncoder.encode(rangeClass.getURI(), "UTF-8") + "\">" + rangeWLang.getPickListName() + "</a>"; } } catch (UnsupportedEncodingException e) { log.error(e, e); } } } results.add(rangeStr); // column 8 results.add(p.getTransitive() ? "true" : "false"); // column 9 results.add(p.getSymmetric() ? "true" : "false"); // column 10 results.add(p.getFunctional() ? "true" : "false"); // column 11 results.add(p.getInverseFunctional() ? "true" : "false"); // column 12 String publicDescriptionStr = (p.getPublicDescription() == null) ? "" : p.getPublicDescription(); results.add(publicDescriptionStr); // column 13 String exampleStr = (p.getExample() == null) ? "" : p.getExample(); results.add(exampleStr); // column 14 String descriptionStr = (p.getDescription() == null) ? "" : p.getDescription(); results.add(descriptionStr); // column 15 results.add(p.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)" : p.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel()); // column 16 results.add(p.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)" : p.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel()); // column 17 results.add("property: " + p.getDomainDisplayTier() + ", inverse: " + p.getRangeDisplayTier()); // column 18 results.add("property: " + p.getDomainDisplayLimitInteger() + ", inverse: " + p.getRangeDisplayLimit()); results.add(p.getCollateBySubclass() ? "true" : "false"); // column 19 results.add(p.getCustomEntryForm() == null ? "(unspecified)" : p.getCustomEntryForm()); // column 20 results.add(p.getSelectFromExisting() ? "true" : "false"); // column 21 results.add(p.getOfferCreateNewOption() ? "true" : "false"); // column 22 results.add(p.getDomainEntitySortDirection() == null ? "ascending" : p.getDomainEntitySortDirection()); // column 23 results.add(p.getURI()); // column 24 results.add(p.getHiddenFromPublishBelowRoleLevel() == null ? "(unspecified)" : p.getHiddenFromPublishBelowRoleLevel().getDisplayLabel()); // column 25 request.setAttribute("results", results); request.setAttribute("columncount", NUM_COLS); request.setAttribute("suppressquery", "true"); EditProcessObject epo = super.createEpo(request, FORCE_NEW); FormObject foo = new FormObject(); HashMap<String, List<Option>> OptionMap = new HashMap<>(); foo.setOptionLists(OptionMap); epo.setFormObject(foo); // superproperties and subproperties ObjectPropertyDao opDao = vreq.getUnfilteredAssertionsWebappDaoFactory().getObjectPropertyDao(); List<ObjectProperty> superProps = getObjectPropertiesForURIList( opDao.getSuperPropertyURIs(p.getURI(), false), opDao); sortForPickList(superProps, vreq); request.setAttribute("superproperties", superProps); List<ObjectProperty> subProps = getObjectPropertiesForURIList(opDao.getSubPropertyURIs(p.getURI()), opDao); sortForPickList(subProps, vreq); request.setAttribute("subproperties", subProps); // equivalent properties and faux properties List<ObjectProperty> eqProps = getObjectPropertiesForURIList(opDao.getEquivalentPropertyURIs(p.getURI()), opDao); sortForPickList(eqProps, vreq); request.setAttribute("equivalentProperties", eqProps); List<FauxProperty> fauxProps = vreq.getUnfilteredAssertionsWebappDaoFactory().getFauxPropertyDao() .getFauxPropertiesForBaseUri(p.getURI()); sortForPickList(fauxProps, vreq); request.setAttribute("fauxproperties", fauxProps); RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); request.setAttribute("epoKey", epo.getKey()); request.setAttribute("propertyWebapp", p); request.setAttribute("bodyJsp", "/templates/edit/specific/props_edit.jsp"); request.setAttribute("title", "Object Property Control Panel"); request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + vreq.getAppBean().getThemeDir() + "css/edit.css\"/>"); try { rd.forward(request, response); } catch (Exception e) { log.error("PropertyEditController could not forward to view."); log.error(e.getMessage()); log.error(e.getStackTrace()); } }
From source file:org.auraframework.http.AuraTestFilter.java
private void innerFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; TestContext testContext = getTestContext(request); boolean doResetTest = testReset.get(request, false); if (testContext != null && doResetTest) { testContext.getLocalDefs().clear(); }// w w w .j a v a2s . com // Check for requests to execute a JSTest, i.e. initial component GETs with particular parameters. if ("GET".equals(request.getMethod())) { DefDescriptor<?> targetDescriptor = getTargetDescriptor(request); if (targetDescriptor != null) { // Check if a single jstest is being requested. String testToRun = jstestToRun.get(request); if (testToRun != null && !testToRun.isEmpty() && !NO_RUN.equals(testToRun)) { AuraContext context = contextService.getCurrentContext(); Format format = context.getFormat(); switch (format) { case HTML: LOG.info(this + " jstest request: " + request.getRequestURL() + "?" + request.getQueryString(), new Error()); TestCaseDef testDef; String targetUri; try { TestSuiteDef suiteDef = getTestSuite(targetDescriptor); testDef = getTestCase(suiteDef, testToRun); testDef.validateDefinition(); if (testContext == null) { testContext = testContextAdapter.getTestContext(testDef.getQualifiedName()); } targetUri = buildJsTestTargetUri(targetDescriptor, testDef); } catch (QuickFixException e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); servletUtilAdapter.setNoCache(response); response.setContentType(servletUtilAdapter.getContentType(Format.HTML)); response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); response.getWriter().append(e.getMessage()); exceptionAdapter.handleException(e); return; } // Load any test mocks. Collection<Definition> mocks = testDef.getLocalDefs(); testContext.getLocalDefs().addAll(mocks); loadTestMocks(context, true, testContext.getLocalDefs()); // Capture the response and inject tags to load jstest. String capturedResponse = captureResponse(request, response, testToRun, targetUri); if (capturedResponse != null) { servletUtilAdapter.setNoCache(response); response.setContentType(servletUtilAdapter.getContentType(Format.HTML)); response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); if (!contextService.isEstablished()) { // There was an error in the original response, so just write the response out. response.getWriter().write(capturedResponse); } else { int timeout = testTimeout.get(request, DEFAULT_JSTEST_TIMEOUT); String testTag = buildJsTestScriptTag(targetDescriptor, testToRun, timeout, capturedResponse); injectScriptTags(response.getWriter(), capturedResponse, testTag); } return; } case JS: servletUtilAdapter.setNoCache(response); response.setContentType(servletUtilAdapter.getContentType(Format.JS)); response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); int timeout = testTimeout.get(request, DEFAULT_JSTEST_TIMEOUT); writeJsTestScript(response.getWriter(), targetDescriptor, testToRun, timeout); return; default: // Pass it on. } } else if (testToRun != null && testToRun.isEmpty()) { Object origRequest = request.getAttribute(AuraResourceServlet.ORIG_REQUEST_URI); LOG.error(this + " empty jstestrun: " + request.getRequestURL() + "?" + request.getQueryString() + " original request: " + origRequest, new Error()); } // aurajstest:jstest app is invokable in the following ways: // ?aura.mode=JSTEST - run all tests // ?aura.mode JSTEST&test=XXX - run single test // ?aura.jstest - run all tests // ?aura.jstest=XXX - run single test // TODO: delete JSTEST mode String jstestAppRequest = jstestAppFlag.get(request); Mode mode = AuraContextFilter.mode.get(request, Mode.PROD); if (mode == Mode.JSTEST || mode == Mode.JSTESTDEBUG || jstestAppRequest != null) { mode = mode.toString().endsWith("DEBUG") ? Mode.AUTOJSTESTDEBUG : Mode.AUTOJSTEST; String qs = String.format("descriptor=%s&defType=%s", targetDescriptor.getDescriptorName(), targetDescriptor.getDefType().name()); String testName = null; if (jstestAppRequest != null && !jstestAppRequest.isEmpty()) { testName = jstestAppRequest; } else if (testToRun != null && !testToRun.isEmpty()) { testName = testToRun; } if (testName != null) { qs = qs + "&test=" + testName; } String newUri = createURI("aurajstest", "jstest", DefType.APPLICATION, mode, Format.HTML, Authentication.AUTHENTICATED.name(), NO_RUN, qs); RequestDispatcher dispatcher = request.getServletContext().getContext(newUri) .getRequestDispatcher(newUri); if (dispatcher != null) { dispatcher.forward(request, response); return; } } } } // Handle mock definitions specified in the tests. if (testContext == null) { // During manual testing, the test context adapter may not always get cleared. testContextAdapter.clear(); } else { if (!contextService.isEstablished()) { LOG.error(this + " Aura context is not established! New context will NOT be created."); chain.doFilter(request, response); return; } AuraContext context = contextService.getCurrentContext(); // Reset mocks if requested, or for the initial GET. loadTestMocks(context, doResetTest, testContext.getLocalDefs()); } chain.doFilter(request, response); }
From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java
/** * Processes the request made from the HTML visual interface of Strabon Endpoint. * /*from ww w. j a va 2s. c o m*/ * @param request * @param response * @throws ServletException * @throws IOException */ private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher; // check whether Update submit button was fired String reqFuncionality = (request.getParameter("submit") == null) ? "" : request.getParameter("submit"); if (reqFuncionality.equals("Update")) { // get the dispatcher for forwarding the rendering of the response dispatcher = request.getRequestDispatcher("/Update"); dispatcher.forward(request, response); } else { String query = URLDecoder.decode(request.getParameter("query"), "UTF-8"); String format = request.getParameter("format"); String handle = request.getParameter("handle"); String maxLimit = request.getParameter("maxLimit"); // get stSPARQLQueryResultFormat from given format name TupleQueryResultFormat queryResultFormat = stSPARQLQueryResultFormat.valueOf(format); if (query == null || format == null || queryResultFormat == null) { dispatcher = request.getRequestDispatcher("query.jsp"); request.setAttribute(ERROR, PARAM_ERROR); dispatcher.forward(request, response); } else { query = strabonWrapper.addLimit(query, maxLimit); if ("download".equals(handle)) { // download as attachment ServletOutputStream out = response.getOutputStream(); response.setContentType(queryResultFormat.getDefaultMIMEType()); response.setHeader("Content-Disposition", "attachment; filename=results." + queryResultFormat.getDefaultFileExtension() + "; " + queryResultFormat.getCharset()); try { strabonWrapper.query(query, format, out); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.print(ResponseMessages.getXMLHeader()); out.print(ResponseMessages.getXMLException(e.getMessage())); out.print(ResponseMessages.getXMLFooter()); } out.flush(); } else if (("map".equals(handle) || "map_local".equals(handle) || "timemap".equals(handle)) && (queryResultFormat == stSPARQLQueryResultFormat.KML || queryResultFormat == stSPARQLQueryResultFormat.KMZ)) { // show map (only valid for KML/KMZ) // get dispatcher dispatcher = request.getRequestDispatcher("query.jsp"); // re-assign handle request.setAttribute("handle", handle); SecureRandom random = new SecureRandom(); String temp = new BigInteger(130, random).toString(32); // the temporary KML/KMZ file to create in the server String tempKMLFile = temp + "." + queryResultFormat.getDefaultFileExtension(); ; try { Date date = new Date(); // get the absolute path of the temporary directory if (!request.getParameter("handle").toString().contains("timemap")) { tempDirectory = appName + "-temp"; basePath = context.getRealPath("/") + "/../ROOT/" + tempDirectory + "/"; // fix the temporary directory for this web application FileUtils.forceMkdir(new File(basePath)); @SuppressWarnings("unchecked") Iterator<File> it = FileUtils.iterateFiles(new File(basePath), null, false); while (it.hasNext()) { File tbd = new File((it.next()).getAbsolutePath()); if (FileUtils.isFileOlder(new File(tbd.getAbsolutePath()), date.getTime())) { FileUtils.forceDelete(new File(tbd.getAbsolutePath())); } } } else { //timemap case tempDirectory = "js/timemap"; basePath = context.getRealPath("/") + tempDirectory + "/"; // fix the temporary directory for this web application } // fix the temporary directory for this web application // create temporary KML/KMZ file File file = new File(basePath + tempKMLFile); // if file does not exist, then create it if (!file.exists()) { file.createNewFile(); } try { // query and write the result in the temporary KML/KMZ file FileOutputStream fos = new FileOutputStream(basePath + tempKMLFile); strabonWrapper.query(query, format, fos); fos.close(); if (request.getParameter("handle").toString().contains("timemap")) { request.setAttribute("pathToKML", tempDirectory + "/" + tempKMLFile); } else { request.setAttribute("pathToKML", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + tempDirectory + "/" + tempKMLFile); } } catch (MalformedQueryException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage()); request.setAttribute(ERROR, e.getMessage()); } catch (Exception e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); request.setAttribute(ERROR, e.getMessage()); } dispatcher.forward(request, response); } catch (IOException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); } } else { // "plain" is assumed as the default dispatcher = request.getRequestDispatcher("query.jsp"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { strabonWrapper.query(query, format, bos); if (format.equals(Common.getHTMLFormat())) { request.setAttribute(RESPONSE, bos.toString()); } else if (format.equals(Format.PIECHART.toString()) || format.equals(Format.AREACHART.toString()) || format.equals(Format.COLUMNCHART.toString())) { request.setAttribute("format", "CHART"); request.setAttribute(RESPONSE, strabonWrapper.getgChartString()); } else { request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString())); } } catch (MalformedQueryException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage()); request.setAttribute(ERROR, e.getMessage()); } catch (Exception e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); request.setAttribute(ERROR, e.getMessage()); } finally { dispatcher.forward(request, response); } } } } }
From source file:com.alfaariss.oa.profile.aselect.processor.handler.BrowserHandler.java
private void forwardToAutoRedirect(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse, String sRedirect, IRequestor oRequestor) throws ASelectException { try {// www.jav a 2 s . co m oServletRequest.setAttribute("redirect", sRedirect); if (oRequestor != null) {//Add requestor object as attribute oServletRequest.setAttribute(IRequestor.REQUESTOR_ATTRIBUTE_NAME, oRequestor); } oServletRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer()); RequestDispatcher oDispatcher = oServletRequest.getRequestDispatcher(_sRedirectJspPath); if (oDispatcher != null) oDispatcher.forward(oServletRequest, oServletResponse); } catch (Exception e) { _logger.fatal("Internal error during forward to auto redirect page", e); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } }
From source file:com.alfaariss.oa.util.saml2.profile.AbstractSAML2Profile.java
/** * Forwards the user to the OA WebSSO Servlet. * <br>// w ww. ja va2s . c om * Before forwarding the session.setProfileURL() is set and the session is * added as an attribute in the request . * @param request The servlet request. * @param response The servlet response. * @param session The user session * @throws OAException If the user can't be forwarded. */ protected void forwardUser(HttpServletRequest request, HttpServletResponse response, ISession session) throws OAException { try { StringBuffer sbProfileUrl = new StringBuffer(); sbProfileUrl.append(_sProfileURL); sbProfileUrl.append("?"); sbProfileUrl.append(ISession.ID_NAME); sbProfileUrl.append("="); sbProfileUrl.append(session.getId()); session.setProfileURL(sbProfileUrl.toString()); request.setAttribute(ISession.ID_NAME, session); RequestDispatcher oDispatcher = request.getRequestDispatcher(_sWebSSOPath); if (oDispatcher == null) { _logger.warn("There is no requestor dispatcher supported with name: " + _sWebSSOPath); throw new OAException(SystemErrors.ERROR_INTERNAL); } oDispatcher.forward(request, response); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not forward user", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.DatapropRetryController.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) { return;/* w w w .j a v a 2s . co m*/ } //create an EditProcessObject for this and put it in the session EditProcessObject epo = super.createEpo(request); epo.setBeanClass(DataProperty.class); VitroRequest vreq = new VitroRequest(request); WebappDaoFactory wadf = ModelAccess.on(getServletContext()).getWebappDaoFactory(); DatatypeDao dDao = wadf.getDatatypeDao(); DataPropertyDao dpDao = wadf.getDataPropertyDao(); epo.setDataAccessObject(dpDao); OntologyDao ontDao = wadf.getOntologyDao(); DataProperty objectForEditing = null; String action = null; if (epo.getAction() == null) { action = "insert"; epo.setAction("insert"); } else { action = epo.getAction(); } if (epo.getUseRecycledBean()) { objectForEditing = (DataProperty) epo.getNewBean(); } else { String uri = request.getParameter("uri"); if (uri != null) { try { objectForEditing = dpDao.getDataPropertyByURI(uri); epo.setOriginalBean(objectForEditing); action = "update"; epo.setAction("update"); } catch (NullPointerException e) { log.error("Need to implement 'record not found' error message."); } } else { action = "insert"; epo.setAction("insert"); objectForEditing = new DataProperty(); epo.setOriginalBean(objectForEditing); } } //put this in the parent class? //make a simple mask for the class's id Object[] simpleMaskPair = new Object[2]; simpleMaskPair[0] = "URI"; simpleMaskPair[1] = objectForEditing.getURI(); epo.getSimpleMask().add(simpleMaskPair); //set any validators LinkedList lnList = new LinkedList(); lnList.add(new XMLNameValidator()); epo.getValidatorMap().put("LocalName", lnList); LinkedList vlist = new LinkedList(); vlist.add(new IntValidator(0, 99)); epo.getValidatorMap().put("StatusId", vlist); //set the getMethod so we can retrieve a new bean after we've inserted it try { Class[] args = new Class[1]; args[0] = String.class; epo.setGetMethod(dpDao.getClass().getDeclaredMethod("getDataPropertyByURI", args)); } catch (NoSuchMethodException e) { log.error("DatapropRetryController could not find the getDataPropertyByURI method in the facade"); } //make a postinsert pageforwarder that will send us to a new class's fetch screen epo.setPostInsertPageForwarder(new DataPropertyInsertPageForwarder()); //make a postdelete pageforwarder that will send us to the list of properties epo.setPostDeletePageForwarder(new UrlForwarder("listDatatypeProperties")); //set up any listeners List changeListenerList = new ArrayList(); changeListenerList.add(new PropertyRestrictionListener()); epo.setChangeListenerList(changeListenerList); FormObject foo = new FormObject(); foo.setErrorMap(epo.getErrMsgMap()); // retain error messages from previous time through the form epo.setFormObject(foo); FormUtils.populateFormFromBean(objectForEditing, action, foo); //for now, this is also making the value hash - need to separate this out HashMap optionMap = new HashMap(); List namespaceList = FormUtils.makeOptionListFromBeans(ontDao.getAllOntologies(), "URI", "Name", ((objectForEditing.getNamespace() == null) ? "" : objectForEditing.getNamespace()), null, (objectForEditing.getNamespace() != null)); namespaceList.add(0, new Option(vreq.getUnfilteredWebappDaoFactory().getDefaultNamespace(), "default")); optionMap.put("Namespace", namespaceList); List<Option> domainOptionList = FormUtils.makeVClassOptionList(vreq.getUnfilteredWebappDaoFactory(), objectForEditing.getDomainClassURI()); if (objectForEditing.getDomainClassURI() != null) { VClass domain = vreq.getWebappDaoFactory().getVClassDao() .getVClassByURI(objectForEditing.getDomainClassURI()); if (domain != null && domain.isAnonymous()) { domainOptionList.add(0, new Option(domain.getURI(), domain.getName(), true)); } } domainOptionList.add(0, new Option("", "(none specified)")); optionMap.put("DomainClassURI", domainOptionList); List datatypeOptionList = FormUtils.makeOptionListFromBeans(dDao.getAllDatatypes(), "Uri", "Name", objectForEditing.getRangeDatatypeURI(), null); datatypeOptionList.add(0, new Option("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral", "XML literal (allows XHTML markup)")); datatypeOptionList.add(0, new Option(null, "untyped (use if language tags desired)")); optionMap.put("RangeDatatypeURI", datatypeOptionList); List groupOptList = FormUtils.makeOptionListFromBeans( vreq.getUnfilteredWebappDaoFactory().getPropertyGroupDao().getPublicGroups(true), "URI", "Name", ((objectForEditing.getGroupURI() == null) ? "" : objectForEditing.getGroupURI()), null, (objectForEditing.getGroupURI() != null)); HashMap<String, Option> hashMap = new HashMap<String, Option>(); groupOptList = getSortedList(hashMap, groupOptList, vreq); groupOptList.add(0, new Option("", "none")); optionMap.put("GroupURI", groupOptList); optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getDisplayOptionsList(objectForEditing)); optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getUpdateOptionsList(objectForEditing)); optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getPublishOptionsList(objectForEditing)); foo.setOptionLists(optionMap); request.setAttribute("functional", objectForEditing.getFunctional()); //checkboxes are pretty annoying : we don't know if someone *unchecked* a box, so we have to default to false on updates. if (objectForEditing.getURI() != null) { objectForEditing.setFunctional(false); } foo.setErrorMap(epo.getErrMsgMap()); RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp"); request.setAttribute("colspan", "4"); request.setAttribute("scripts", "/templates/edit/formBasic.js"); request.setAttribute("formJsp", "/templates/edit/specific/dataprop_retry.jsp"); request.setAttribute("title", "Data Property Editing Form"); request.setAttribute("_action", action); request.setAttribute("unqualifiedClassName", "DatatypeProperty"); setRequestAttributes(request, epo); try { rd.forward(request, response); } catch (Exception e) { log.error("DatatypeRetryController could not forward to view."); log.error(e.getMessage()); log.error(e.getStackTrace()); } }
From source file:com.alfaariss.oa.profile.aselect.processor.handler.BrowserHandler.java
private void showErrorPage(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse, UserEvent oEvent, String sCode, ISession oSession) throws ASelectException { try {/* ww w. j a va 2 s.c om*/ if (oEvent != null) { oServletRequest.setAttribute(UserException.USEREVENT_NAME, oEvent); } List<String> details = new Vector<String>(); details.add(sCode); oServletRequest.setAttribute(DetailedUserException.DETAILS_NAME, details); if (oSession != null) { String sRequestorID = oSession.getRequestorId(); if (sRequestorID != null) { IRequestor oRequestor = _requestorPoolFactory.getRequestor(sRequestorID); if (oRequestor != null) oServletRequest.setAttribute(IRequestor.REQUESTOR_ATTRIBUTE_NAME, oRequestor); } oServletRequest.setAttribute(ISession.LOCALE_NAME, oSession.getLocale()); oServletRequest.setAttribute(ISession.ID_NAME, oSession.getId()); } oServletRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer()); RequestDispatcher oDispatcher = oServletRequest.getRequestDispatcher(_sErrorJspPath); if (oDispatcher != null) oDispatcher.forward(oServletRequest, oServletResponse); } catch (Exception e) { _logger.fatal("Internal error during showing the error page", e); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } }
From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java
private void parseReq(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w. j av a 2 s. c om*/ MF mf = MF.getFactory(); req.setCharacterEncoding("UTF-8"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); HashMap<String, String> map = new HashMap<String, String>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String field = item.getFieldName(); String value = Streams.asString(stream); map.put(field, value); stream.close(); } else { String filename = item.getName(); String[] extension = filename.split("\\."); String mail = map.get("mail"); if (mail != null) { filename = mail + "_" + String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } else { filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } map.put("filename", filename); byte[] buffer = IOUtils.toByteArray(stream); mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer, filename); stream.close(); } } String email = map.get("mail"); String firstName = map.get("firstName"); String lastName = map.get("lastName"); String dayS = map.get("day"); String monthS = map.get("month"); String yearS = map.get("year"); String password = map.get("password"); String filename = map.get("filename"); String date = yearS + "-" + monthS + "-" + dayS; char gender = map.get("gender").charAt(0); RequestDispatcher disp; Connection c = mf.getSQLService().getConnection(); String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')"; Statement statement = c.createStatement(); statement.executeUpdate(stm); statement.close(); c.close(); req.getSession(true).setAttribute("actualUser", email); req.getSession(true).setAttribute("edit", "false"); disp = req.getRequestDispatcher("SelectTopic.jsp"); disp.forward(req, response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } }