List of usage examples for javax.servlet RequestDispatcher forward
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;
From source file:myClass_Main.java
/** * * @param request//from w w w .j a va 2s . c o m * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int option = Integer.parseInt(request.getParameter("optionValue")); String url; // do some processing here... // get response writer switch (option) { case 1: { int userValue = Integer.parseInt(request.getParameter("userValue")); String htmlres = ""; // build HTML code for (int i = 0; i < userValue; i++) { htmlres = htmlres + "<input type=\"text\" id=\"inputValue\" name=\"inputValue\" class=\"form-group form-control\" placeholder=\"Nombre de Pais " + (i + 1) + "\" required autofocus>"; } request.setAttribute("htmlres", htmlres); url = "/myPage_core.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; case 2: { String[] input = request.getParameterValues("inputValue"); String sourceURL = "http://api.myjson.com/bins/vcv1"; //just a string // Connect to the URL using java's native library URL urlobject = new URL(sourceURL); HttpURLConnection conection = (HttpURLConnection) urlobject.openConnection(); conection.connect(); // Convert to a JSON object to print data String[][] contry_values = new String[10][input.length]; String zipcode = null; JSONParser jp = new JSONParser(); //from gson JSONObject root = null; JSONArray root_array = null; try { root = (JSONObject) jp.parse(new InputStreamReader(conection.getInputStream())); //Convert the input stream to a json element } catch (ParseException ex) { Logger.getLogger(myClass_Main.class.getName()).log(Level.SEVERE, null, ex); } boolean firstName = (boolean) root.containsKey("countries"); root = (JSONObject) root.get("countries"); root_array = (JSONArray) root.get("country"); //Iterator j = root_array.iterator(); for (int i = 0; i < input.length; i++) { Iterator j = root_array.iterator(); while (j.hasNext()) { JSONObject inner = (JSONObject) j.next(); if (inner.containsValue(input[i])) { contry_values[0][i] = (String) inner.get("isoNumeric"); contry_values[1][i] = (String) inner.get("countryName"); contry_values[2][i] = (String) inner.get("continentName"); contry_values[3][i] = (String) inner.get("capital"); contry_values[4][i] = (String) inner.get("languages"); if (contry_values[4][i].length() > 11) { String strOut = contry_values[4][i]; String trimedstring = strOut.substring(0, 10) + "...";// count start in 0 and 8 is excluded contry_values[4][i] = trimedstring; } contry_values[5][i] = (String) inner.get("population"); contry_values[6][i] = (String) inner.get("areaInSqKm"); contry_values[7][i] = (String) inner.get("countryCode"); contry_values[8][i] = "https://es.wikipedia.org/wiki/" + ((String) inner.get("countryName")); } } } System.out.println("The first name is: " + zipcode); request.setAttribute("firstname", zipcode); String htmlres = "<table class=\"table\">\n" + "<caption>Datos de Paises</caption>\n" + "<thead>\n" + "<tr>\n" + "<th>COD INT.</th>\n" + "<th>AVB.</th>\n" + "<th>Nombre</th>\n" + "<th>Continente</th>\n" + "<th>Capital</th>\n" + "<th>Idioma</th>\n" + "<th>Poblacion</th>\n" + "<th>Area km2</th>\n" + "<th>Wiki URL</th>\n" + "</tr>\n" + "</thead>\n" + "<tbody>"; // build HTML code for (int h = 0; h < input.length; h++) { if ((contry_values[0][h]) != null) { htmlres = htmlres + "<tr><th scope=\"row\">" + contry_values[0][h] + "</th>"; for (int g = 0; g < 9; g++) { if (g != 8) { htmlres = htmlres + "<td>" + contry_values[g][h] + "</td>"; } else { htmlres = htmlres + "<td>" + "<a href=\"" + contry_values[g][h] + "\" class=\"btn btn-info\" role=\"button\">" + contry_values[7][h] + "</a>" + "</td>"; } } htmlres = htmlres + "</tr>"; } else { htmlres = htmlres + "<tr><th scope=\"row\">" + "#Er." + h + "</th>"; htmlres = htmlres + "<td colspan=\"9\">" + "El pais \"" + input[h] + "\" no esta en la BD, verifique que el nombre esta en ingls, e intente de nuevo" + "</td>"; } } htmlres = htmlres + "<tr>"; htmlres = htmlres + "</tbody>\n" + "</table>"; request.setAttribute("htmlres", htmlres); url = "/myPage_res.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; case 3: { url = "/index.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; default: { url = "/index.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; } }
From source file:Ctrl.CtrlProducts.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww.ja va2 s. c o 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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String action = request.getParameter("action"); if (action.equals("Tm Kim")) { String name = request.getParameter("txtTenSP"); Products sp = new Products(); List<Product> list = new ArrayList<Product>(); list = sp.HienthiSPadmin(name); request.setAttribute("listSP", list); RequestDispatcher rd = request.getRequestDispatcher("Product.jsp"); rd.forward(request, response); } else if (action.equals("Delete")) { String code = request.getParameter("txtcode"); Products sp = new Products(); sp.delete(code); String url = "Product.jsp"; RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } else if (action.equals("Edit")) { String code = request.getParameter("txtcode").trim(); String name = request.getParameter("txtname"); String pri = request.getParameter("txtprice"); String manhinh = request.getParameter("txtmanhinh"); String ram = request.getParameter("txtram"); String hdd = request.getParameter("txthdd"); String cpu = request.getParameter("txtcpu"); String khuyenmai = request.getParameter("txtkhuyenmai"); String baohanh = request.getParameter("txtbaohanh"); String hinh = request.getParameter("txthinh"); int nkhuyenmai = Integer.parseInt(khuyenmai); float fpri = Float.parseFloat(pri); Product sp = new Product(code, name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh); request.setAttribute("SP", sp); RequestDispatcher rd = request.getRequestDispatcher("chinhsuasp.jsp"); rd.forward(request, response); } else if (action.equals("Update")) { String code = request.getParameter("txtcode"); String name = request.getParameter("txtname"); String pri = request.getParameter("txtprice"); String manhinh = request.getParameter("txtmanhinh"); String ram = request.getParameter("txtram"); String hdd = request.getParameter("txthdd"); String cpu = request.getParameter("txtcpu"); String khuyenmai = request.getParameter("txtkhuyenmai"); String baohanh = request.getParameter("txtbaohanh"); String hinh = request.getParameter("txthinh"); String ten = request.getParameter("txtTenSP"); int nkhuyenmai = Integer.parseInt(khuyenmai); float fpri = Float.parseFloat(pri); String url = "Product.jsp"; Products sp = new Products(); sp.insert(name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh, code); RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } else if (action.equals("Thm")) { String code = request.getParameter("txtcode"); String name = request.getParameter("txtname"); String pri = request.getParameter("txtprice"); String manhinh = request.getParameter("txtmanhinh"); String ram = request.getParameter("txtram"); String hdd = request.getParameter("txthdd"); String cpu = request.getParameter("txtcpu"); String khuyenmai = request.getParameter("txtkhuyenmai"); String baohanh = request.getParameter("txtbaohanh"); String hinh = request.getParameter("txthinh"); int nkhuyenmai = Integer.parseInt(khuyenmai); float fpri = Float.parseFloat(pri); Products sp = new Products(); sp.newsp(code, name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh); RequestDispatcher rd = request.getRequestDispatcher("CtrlProducts?action=Tm+Kim&txtTenSP"); rd.forward(request, response); } else if (action.equals("Thm Sn Phm")) { RequestDispatcher rd = request.getRequestDispatcher("newsp.jsp"); rd.forward(request, response); } else if (action.equals("Qun l ti khon")) { RequestDispatcher rd = request.getRequestDispatcher("Quanliuser.jsp"); rd.forward(request, response); } if (action.equals("Logout")) { HttpSession session = request.getSession(true); session.invalidate(); RequestDispatcher rd = request.getRequestDispatcher("Trangchu.jsp"); rd.forward(request, response); } } catch (Exception e) { e.printStackTrace(); } }
From source file:edu.lternet.pasta.portal.BrowseServlet.java
/** * The doPost method of the servlet. <br> * //from w w w .j a va 2s .c o m * This method is called when a form has its tag value method equals to post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forward = "./searchResult.jsp"; String html = null; TermsList termsList = null; String termsListHTML = ""; String xml = null; HttpSession httpSession = request.getSession(); String uid = (String) httpSession.getAttribute("uid"); if (uid == null || uid.isEmpty()) { uid = "public"; } String searchValue = request.getParameter("searchValue"); BrowseTerm browseTerm = new BrowseTerm(searchValue); // Tell the web server that the response is HTML response.setContentType("text/html"); try { xml = browseTerm.runQuery(); termsList = browseTerm.getTermsList(); if (termsList != null) { termsListHTML = termsList.toHTML(); } String queryText = browseTerm.getQueryString(); httpSession.setAttribute("queryText", queryText); httpSession.setAttribute("termsListHTML", termsListHTML); ResultSetUtility resultSetUtility = null; if (uid.equals("public")) { resultSetUtility = new ResultSetUtility(xml, Search.DEFAULT_SORT); } else { boolean isSavedDataPage = false; SavedData savedData = new SavedData(uid); resultSetUtility = new ResultSetUtility(xml, Search.DEFAULT_SORT, savedData, isSavedDataPage); } String mapButtonHTML = resultSetUtility.getMapButtonHTML(); request.setAttribute("mapButtonHTML", mapButtonHTML); //String relevanceHTML = resultSetUtility.getRelevanceHTML(); //request.setAttribute("relevanceHTML", relevanceHTML); html = resultSetUtility.xmlToHtmlTable(cwd + xslpath); request.setAttribute("searchresult", html); RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward); requestDispatcher.forward(request, response); } catch (Exception e) { handleDataPortalError(logger, e); } }
From source file:com.sinosoft.one.mvc.web.portal.impl.WindowTask.java
public void run() { try {// ww w . ja va2 s .co m // started window.getContainer().onWindowStarted(window); // doRequest String windowPath = window.getPath(); if (windowPath.length() == 0 || windowPath.charAt(0) != '/') { String requestUri = request.getRequestURI(); if (!requestUri.endsWith("/")) { requestUri = requestUri + "/"; } windowPath = requestUri + windowPath; } // request.setAttribute("$$one-mvc-portal.window", window); request.setAttribute("$$one-mvc-portal.window." + window.getName(), window); // String list = (String)request.getAttribute("$$one-mvc-portal.window.names"); // if(list==null){ // list = window.getName(); // } // else{ // list = list+","+window.getName(); // } // request.setAttribute("$$one-mvc-portal.window.names",list); if (this.response.isCommitted()) { if (logger.isDebugEnabled()) { logger.debug("onWindowTimeout: response has committed. [" + window.getName() + "]@" + window.getContainer()); } window.getContainer().onWindowTimeout(window); return; } final RequestDispatcher rd = request.getRequestDispatcher(windowPath); request.setAttribute(MvcConstants.WINDOW_REQUEST_URI, request.getContextPath() + windowPath); rd.forward(request, this.response); // done! window.getContainer().onWindowDone(window); } catch (Throwable e) { logger.error("", e); window.setThrowable(e); window.getContainer().onWindowError(window); } finally { // remove request from ThreadLocal in PortalRequest // ?PortalRequestThreadLocal???? ?request? final HttpServletRequest wrapper = window.getContainer().getRequest(); final PortalRequest portalRequest = PortalRequest.unwrapPortalRequest(wrapper); portalRequest.setRequest(null); } }
From source file:com.francelabs.datafari.servlets.URL.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)//from w w w . j ava 2 s. c om */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); final String protocol = request.getScheme() + ":"; final Map<String, String[]> requestMap = new HashMap<>(); requestMap.putAll(request.getParameterMap()); final IndexerQuery query = IndexerServerManager.createQuery(); query.addParams(requestMap); // get the AD domain String domain = ""; HashMap<String, String> h; try { h = RealmLdapConfiguration.getConfig(request); if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) { final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase(); final String[] parts = userBase.split(","); domain = ""; for (int i = 0; i < parts.length; i++) { if (parts[i].indexOf("dc=") != -1) { // Check if the current // part is a domain // component if (!domain.isEmpty()) { domain += "."; } domain += parts[i].substring(parts[i].indexOf('=') + 1); } } } // Add authentication if (request.getUserPrincipal() != null) { String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", ""); if (AuthenticatedUserName.contains("@")) { AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@")); } if (!domain.equals("")) { AuthenticatedUserName += "@" + domain; } query.setParam("AuthenticatedUserName", AuthenticatedUserName); } } catch (final Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } StatsPusher.pushDocument(query, protocol); // String surl = URLDecoder.decode(request.getParameter("url"), // "ISO-8859-1"); final String surl = request.getParameter("url"); if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true") && !surl.startsWith("file://///")) { final int BUFSIZE = 4096; String fileName = null; /** * File Display/Download --> <!-- Written by Rick Garcia --> */ if (SystemUtils.IS_OS_LINUX) { // try to open the file locally final String fileNameA[] = surl.split(":"); fileName = URLDecoder.decode(fileNameA[1], "UTF-8"); } else if (SystemUtils.IS_OS_WINDOWS) { fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", ""); } final File file = new File(fileName); int length = 0; final ServletOutputStream outStream = response.getOutputStream(); final ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType(fileName); // sets response content type if (mimetype == null) { mimetype = "application/octet-stream"; } response.setContentType(mimetype); response.setContentLength((int) file.length()); // sets HTTP header response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\""); final byte[] byteBuffer = new byte[BUFSIZE]; final DataInputStream in = new DataInputStream(new FileInputStream(file)); // reads the file's bytes and writes them to the response stream while (in != null && (length = in.read(byteBuffer)) != -1) { outStream.write(byteBuffer, 0, length); } in.close(); outStream.close(); } else { final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl); rd.forward(request, response); } }
From source file:eu.eidas.node.service.ColleagueRequestServlet.java
/** * Post method/*w w w . j ava 2 s. com*/ * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PropertiesUtil.checkProxyServiceActive(); // Obtaining the assertion consumer url from SPRING context ServiceControllerService controllerService = (ServiceControllerService) getApplicationContext() .getBean(NodeBeanNames.EIDAS_SERVICE_CONTROLLER.toString()); CorrelationMap<StoredAuthenticationRequest> requestCorrelationMap = controllerService .getProxyServiceRequestCorrelationMap(); // Prevent cookies from being accessed through client-side script WITHOUT renew of session. setHTTPOnlyHeaderToSession(false, request, response); SessionHolder.setId(request.getSession()); request.getSession().setAttribute(EidasParameterKeys.SAML_PHASE.toString(), EIDASValues.EIDAS_SERVICE_REQUEST); // Obtains the parameters from httpRequest WebRequest webRequest = new IncomingRequest(request); // Validating the only HTTP parameter: SAMLRequest. String samlRequest = webRequest.getEncodedLastParameterValue(EidasParameterKeys.SAML_REQUEST); NodeParameterValidator.paramName(EidasParameterKeys.SAML_REQUEST).paramValue(samlRequest) .eidasError(EidasErrorKey.COLLEAGUE_REQ_INVALID_SAML).validate(); // Storing the Remote Address and Host for auditing proposes. String remoteIpAddress = webRequest.getRemoteIpAddress(); // Validating the optional HTTP Parameter relayState. String relayState = webRequest.getEncodedLastParameterValue(NodeParameterNames.RELAY_STATE.toString()); LOG.debug("Saving ProxyService relay state. " + relayState); // Obtaining the authData IAuthenticationRequest authData = controllerService.getProxyService() .processAuthenticationRequest(webRequest, relayState, requestCorrelationMap, remoteIpAddress); if (StringUtils.isNotBlank(relayState)) { // RelayState's HTTP Parameter is optional! NodeParameterValidator.paramName(NodeParameterNames.RELAY_STATE).paramValue(relayState) .eidasError(EidasErrorKey.SPROVIDER_SELECTOR_INVALID_RELAY_STATE).validate(); } // Validating the personal attribute list IPersonalAttributeList persAttrList = PersonalAttributeList.copyOf(authData.getRequestedAttributes()); List<PersonalAttribute> attrList = new ArrayList<PersonalAttribute>(); boolean hasEidasAttributes = !Sets.intersection(EidasSpec.REGISTRY.getAttributes(), authData.getRequestedAttributes().getDefinitions()).isEmpty(); //ImmutablePersonalAttributeSet for (PersonalAttribute pa : persAttrList) { attrList.add(pa); } String redirectUrl = authData.getAssertionConsumerServiceURL(); LOG.debug("RedirectUrl: " + redirectUrl); // Validating the citizenConsentUrl NodeParameterValidator.paramName(EidasParameterKeys.EIDAS_SERVICE_REDIRECT_URL) .paramValue(controllerService.getCitizenConsentUrl()) .eidasError(EidasErrorKey.COLLEAGUE_REQ_INVALID_DEST_URL).validate(); LOG.debug("sessionId is on cookies () or fromURL ", request.isRequestedSessionIdFromCookie(), request.isRequestedSessionIdFromURL()); request.setAttribute(NodeParameterNames.SAML_TOKEN_FAIL.toString(), controllerService.getProxyService().generateSamlTokenFail(authData, EIDASStatusCode.REQUESTER_URI.toString(), EidasErrorKey.CITIZEN_RESPONSE_MANDATORY, remoteIpAddress)); request.setAttribute(EidasParameterKeys.SP_ID.toString(), authData.getProviderName()); if (authData instanceof IStorkAuthenticationRequest) { request.setAttribute(NodeParameterNames.QAA_LEVEL.toString(), ((IStorkAuthenticationRequest) authData).getQaa()); } request.setAttribute(NodeParameterNames.LOA_VALUE.toString(), EidasAttributesUtil.getUserFriendlyLoa(authData.getLevelOfAssurance())); request.setAttribute(NodeParameterNames.CITIZEN_CONSENT_URL.toString(), encodeURL(controllerService.getCitizenConsentUrl(), response)); // Correct URl redirect cookie implementation request.setAttribute(NodeParameterNames.ATTR_LIST.toString(), attrList); request.setAttribute(NodeParameterNames.REDIRECT_URL.toString(), encodeURL(redirectUrl, response));// Correct URl redirect cookie implementation request.setAttribute(NodeParameterNames.EIDAS_ATTRIBUTES_PARAM.toString(), Boolean.valueOf(hasEidasAttributes)); request.setAttribute(NodeParameterNames.REQUEST_ID.toString(), authData.getId()); request.setAttribute(NodeParameterNames.COLLEAGUE_REQUEST.toString(), authData); NodeViewNames forwardUrl; if (controllerService.isAskConsentType()) { forwardUrl = NodeViewNames.EIDAS_SERVICE_PRESENT_CONSENT; } else { forwardUrl = NodeViewNames.EIDAS_SERVICE_NO_CONSENT; } RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl.toString()); dispatcher.forward(request, response); }
From source file:org.apache.struts.tiles.commands.TilesPreProcessor.java
/** * <p>Do an include of specified URI using a <code>RequestDispatcher</code>.</p> * * @param context a chain servlet/web context * @param uri Context-relative URI to include *///from ww w . j ava 2 s . c om protected void doForward(ServletActionContext context, String uri) throws IOException, ServletException { RequestDispatcher rd = getRequiredDispatcher(context, uri); if (rd != null) { rd.forward(context.getRequest(), context.getResponse()); } }
From source file:com.alfaariss.oa.util.saml2.binding.artifact.JSPHTTPArtifactEncoder.java
private void postEncode(SAMLMessageContext<SAMLObject, SAMLObject, NameID> artifactContext, HTTPOutTransport outTransport) throws MessageEncodingException { InTransport inTransport = artifactContext.getInboundMessageTransport(); HttpServletRequest request = ((HttpServletRequestAdapter) inTransport).getWrappedRequest(); HttpServletResponse response = ((HttpServletResponseAdapter) outTransport).getWrappedResponse(); request.setAttribute("action", getEndpointURL(artifactContext)); request.setAttribute("SAMLArt", buildArtifact(artifactContext).base64Encode()); if (checkRelayState(artifactContext.getRelayState())) { request.setAttribute("RelayState", HTTPTransportUtils.urlEncode(artifactContext.getRelayState())); }/*from w ww. j a v a 2s . c o m*/ try { _logger.debug("Forward caller to JSP template"); RequestDispatcher oDispatcher = request.getRequestDispatcher(_sTemplateLocation); oDispatcher.forward(request, response); } catch (ServletException e) { _logger.warn("Could not process forward to JSP due to Servlet Error", e); throw new MessageEncodingException("Could not process forward to JSP"); } catch (IOException e) { _logger.warn("Could not process forward to JSP due to I/O Error", e); throw new MessageEncodingException("Could not process forward to JSP"); } }
From source file:controller.servlet.ImportAmenities.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w ww . ja v a 2 s . c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Obtencin de la regin String regionName = request.getParameter("regionname"); boolean isXML = false; // Procesado del fichero para subirlo al servidor. for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.POIS_FOLDER + File.separator + fileName; File directory = new File(path + File.separator + Path.POIS_FOLDER); fileName = FilenameUtils.getBaseName(fileName); if (!directory.exists()) { directory.mkdirs(); } try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } // Comprobacin de que sea un fichero xml. if (extension.equals("xml")) { isXML = true; } else { break; } if (isXML) { // Crear entrada en la tabla de ficheros de PDIs. UploadedPoiFileDaoImpl uPFDao = new UploadedPoiFileDaoImpl(); UploadedFile uFile = new UploadedFile(); uFile.setName(fileName); uFile.setProcessedDate(new java.sql.Date(new java.util.Date().getTime())); uPFDao.createFile(uFile); // Almacenado de los datos en la Base de Datos. NotifyingThread nT = new AmenityProcessing(ruta, regionName); nT.addListener(this); nT.setName(ThreadName.AMENITIES_THREAD_NAME); nT.start(); } } } } HttpSession session = request.getSession(true); session.setAttribute("isXML", isXML); if (!isXML) { session.setAttribute("error", true); String page = "/pages/amenitiesmanage.jsp"; RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page); requestDispatcher.forward(request, response); } else { session.setAttribute("error", false); processRequest(request, response); } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.listing.PropertyGroupsListingController.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) { return;/*from ww w .j a va 2 s.c o m*/ } VitroRequest vreq = new VitroRequest(request); PropertyGroupDao dao = vreq.getUnfilteredWebappDaoFactory().getPropertyGroupDao(); List<PropertyGroup> groups = dao.getPublicGroups(WITH_PROPERTIES); Comparator<Property> comparator = new PropertySorter(vreq.getCollator()); List<String> results = new ArrayList<String>(); results.add("XX"); results.add("group"); results.add("display rank"); results.add(""); results.add("XX"); if (groups != null) { for (PropertyGroup pg : groups) { results.add("XX"); String publicName = pg.getName(); if (StringUtils.isBlank(publicName)) { publicName = "(unnamed group)"; } try { results.add("<a href=\"./editForm?uri=" + URLEncoder.encode(pg.getURI(), "UTF-8") + "&controller=PropertyGroup\">" + publicName + "</a>"); } catch (Exception e) { results.add(publicName); } Integer t; results.add(((t = Integer.valueOf(pg.getDisplayRank())) != -1) ? t.toString() : ""); results.add(""); results.add("XX"); List<Property> propertyList = pg.getPropertyList(); if (propertyList != null && propertyList.size() > 0) { Collections.sort(propertyList, comparator); results.add("+"); results.add("XX"); results.add("property"); results.add(""); results.add(""); results.add("@@entities"); Iterator<Property> propIt = propertyList.iterator(); while (propIt.hasNext()) { Property prop = propIt.next(); results.add("XX"); String controllerStr = "propertyEdit"; String nameStr = (prop.getLabel() == null) ? "" : prop.getLabel(); if (prop instanceof ObjectProperty) { nameStr = ((ObjectProperty) prop).getDomainPublic(); } else if (prop instanceof DataProperty) { controllerStr = "datapropEdit"; nameStr = ((DataProperty) prop).getName(); } if (prop.getURI() != null) { try { results.add("<a href=\"" + controllerStr + "?uri=" + URLEncoder.encode(prop.getURI(), "UTF-8") + "\">" + nameStr + "</a>"); } catch (Exception e) { results.add(nameStr); } } else { results.add(nameStr); } String exampleStr = ""; results.add(exampleStr); String descriptionStr = ""; results.add(descriptionStr); if (propIt.hasNext()) results.add("@@entities"); } } } request.setAttribute("results", results); } request.setAttribute("columncount", new Integer(5)); request.setAttribute("suppressquery", "true"); request.setAttribute("title", "Property Groups"); request.setAttribute("bodyJsp", Controllers.HORIZONTAL_JSP); request.setAttribute("horizontalJspAddButtonUrl", Controllers.RETRY_URL); request.setAttribute("horizontalJspAddButtonText", "Add new property group"); request.setAttribute("horizontalJspAddButtonControllerParam", "PropertyGroup"); RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); try { rd.forward(request, response); } catch (Throwable t) { t.printStackTrace(); } }