Example usage for javax.servlet ServletConfig getServletContext

List of usage examples for javax.servlet ServletConfig getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletConfig getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns a reference to the ServletContext in which the caller is executing.

Usage

From source file:user.controller.ProccessCreate.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww w .  j av  a  2  s.c o  m*/
 * @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 {
    try {
        request.setCharacterEncoding("UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        File filedir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
        factory.setRepository(filedir);
        List items = new ServletFileUpload(factory).parseRequest(request);
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        for (FileItem item : (List<FileItem>) items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("gioiTinh")) {
                    builder.append("\"").append(item.getFieldName()).append("\"" + ":").append("\"")
                            .append(item.getString().equals("Nam") ? 1 : 0).append("\",");
                } else {
                    InputStreamReader inputStreamReader = new InputStreamReader(
                            (InputStream) item.getInputStream(), "UTF-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        builder.append("\"").append(item.getFieldName()).append("\"" + ":").append("\"")
                                .append(line).append("\",");
                    }

                }
            } else {
                if (!"".equals(item.getName())) {
                    builder.append("\"").append(item.getFieldName()).append("\"" + ":").append("\"")
                            .append(item.getName()).append("\",");

                    // get file path
                    ServletConfig config = getServletConfig();
                    ServletContext context = config.getServletContext();
                    String webInfPath = context.getRealPath("static");

                    InputStream inputStream = item.getInputStream();
                    File file = new File(webInfPath + "/images/" + item.getName());
                    //                    file.createNewFile();
                    OutputStream os = new FileOutputStream(file);
                    byte[] buffer = new byte[10 * 1024];
                    for (int length; (length = inputStream.read(buffer)) != -1;) {
                        os.write(buffer, 0, length);
                    }
                }

            }
        }
        builder.deleteCharAt(builder.length() - 1);
        builder.append("}");
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson g = gsonBuilder.create();
        Systemuser systemuser = g.fromJson(builder.toString(), Systemuser.class);
        Systemuserhelper s = new Systemuserhelper();
        if (null == s.create(systemuser)) {
            response.getWriter().write("Fail!!!");
        } else {
            response.getWriter().write("Success");
        }
    } catch (FileUploadException | IOException e) {
        response.getWriter().write("Fail!!!");
        e.printStackTrace();
    }

}

From source file:org.echocat.nodoodle.server.ServiceServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    final WebApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(config.getServletContext());
    final String serviceName = config.getInitParameter(SERVICE_PARAM);
    if (StringUtils.isEmpty(serviceName)) {
        throw new ServletException("Required initParam " + SERVICE_PARAM + " not set.");
    }/*from   w w  w  .j a va 2s .  co  m*/
    try {
        _service = applicationContext.getBean(serviceName, HttpService.class);
    } catch (NoSuchBeanDefinitionException e) {
        throw new ServletException("No service '" + serviceName + "' (defined under initParam '" + SERVICE_PARAM
                + "') could not be found.", e);
    }
    try {
        _service.init(config.getServletContext());
    } catch (Exception e) {
        throw new ServletException("Could not initiate the service: " + _service, e);
    }
}

From source file:org.fao.geonet.monitor.webapp.GeonetworkHealthCheckServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    String registryAttribute = config.getInitParameter(REGISTRY_ATTRIBUTE_KEY);
    registry = (HealthCheckRegistry) config.getServletContext().getAttribute(registryAttribute);
    if (registry == null) {
        throw new IllegalStateException(
                "Expected a HealthCheckRegistery to be registered in the ServletContext attributes but there was none");
    }//from w w  w . j av  a2s.  co m
}

From source file:dk.clarin.tools.rest.upload.java

public void init(ServletConfig config) throws ServletException {
    InputStream fis = config.getServletContext().getResourceAsStream("/WEB-INF/classes/properties.xml");
    ToolsProperties.readProperties(fis);
    BracMat = new bracmat(ToolsProperties.bootBracmat);
    super.init(config);
    destinationDir = new File(ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*/);
    if (!destinationDir.isDirectory()) {
        throw new ServletException("Trying to set \""
                + ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*/
                + "\" as directory for temporary storing intermediate and final results, but this is not a valid directory.");
    }/*from ww  w.  j  a v  a2 s .c o  m*/
}

From source file:org.wso2.carbon.governance.custom.lifecycles.checklist.ui.clients.LifecycleServiceClient.java

public LifecycleServiceClient(String cookie, ServletConfig config, HttpSession session)
        throws RegistryException {

    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
    ConfigurationContext configContext = (ConfigurationContext) config.getServletContext()
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    epr = backendServerURL + "CustomLifecyclesChecklistAdminService";

    try {/*  w ww . j  av a2  s .  c  om*/
        stub = new CustomLifecyclesChecklistAdminServiceStub(configContext, epr);

        ServiceClient client = stub._getServiceClient();
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);

    } catch (AxisFault axisFault) {
        String msg = "Failed to initiate lifecycles service client. " + axisFault.getMessage();
        log.error(msg, axisFault);
        throw new RegistryException(msg, axisFault);
    }
}

From source file:org.granite.grails.web.GrailsWebSWFServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    servletContextLoader = new ServletContextResourceLoader(servletConfig.getServletContext());
    ApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletConfig.getServletContext());
    if (springContext.containsBean(GroovyPageResourceLoader.BEAN_ID)) {
        resourceLoader = (ResourceLoader) springContext.getBean(GroovyPageResourceLoader.BEAN_ID);
    }// w  ww  .  j a  v a  2 s. c o m

    grailsAttributes = new DefaultGrailsApplicationAttributes(servletConfig.getServletContext());
}

From source file:servlets.ParserServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    //super.init(config); //To change body of generated methods, choose Tools | Templates.
    this.context = config.getServletContext();
}

From source file:ai.h2o.servicebuilder.CompilePojoServlet.java

public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    try {//from ww w .j a  v  a2s  .c om
        servletPath = new File(servletConfig.getServletContext().getResource("/").getPath());
        if (VERBOSE)
            logger.info("servletPath = {}", servletPath);
    } catch (MalformedURLException e) {
        logger.error("init failed", e);
    }
}

From source file:jamm.webapp.InitServlet.java

/**
 * Loads the jamm.properties file and uses it to initalize the
 * Globals object./* w  w w  . j  av  a 2s . c  o  m*/
 *
 * @see jamm.webapp.Globals
 *
 * @param config The configuration from the servlet container.
 *
 * @throws ServletException when their is an IOException loading
 *                          the properties file
 */
private void loadProperties(ServletConfig config) throws ServletException {
    String path;
    Properties properties;

    try {
        path = config.getServletContext().getRealPath("WEB-INF/" + "jamm.properties");
        properties = new Properties();
        properties.load(new FileInputStream(path));

        Globals.setLdapHost(getStringProperty(properties, "ldap.host", "localhost"));
        Globals.setLdapPort(getIntProperty(properties, "ldap.port", 389));
        Globals.setLdapSearchBase(getStringProperty(properties, "ldap.search_base", ""));
        LdapPassword
                .setRandomClass(getStringProperty(properties, "random_class", "java.security.SecureRandom"));

        // Strip out leading and trailing quotes (common problem)
        String rootDn = getStringProperty(properties, "ldap.root_dn", "");
        if (rootDn.startsWith("\"") && rootDn.endsWith("\"")) {
            rootDn = StringUtils.substring(rootDn, 1, -1);
        }
        Globals.setRootDn(rootDn);
        Globals.setRootLogin(getStringProperty(properties, "ldap.root_login", "root"));
        MailManagerOptions.setUsePasswordExOp(getBooleanProperty(properties, "password.exop", true));
        MailManagerOptions
                .setVmailHomedir(getStringProperty(properties, "vmail.homedir", "/home/vmail/domains"));
    } catch (IOException e) {
        throw new ServletException(e);
    }

}

From source file:org.wso2.carbon.bpel.ui.bpel2svg.PNGGenarateServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request  servlet request//from   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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Log log = LogFactory.getLog(PNGGenarateServlet.class);
    HttpSession session = request.getSession(true);
    String pid = CharacterEncoder.getSafeText(request.getParameter("pid"));
    ServletConfig config = getServletConfig();
    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
    ConfigurationContext configContext = (ConfigurationContext) config.getServletContext()
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    String processDef;
    ProcessManagementServiceClient client;
    SVGInterface svg;
    String svgStr;
    try {
        client = new ProcessManagementServiceClient(cookie, backendServerURL, configContext,
                request.getLocale());
        //Gets the bpel process definition needed to create the SVG from the processId
        processDef = client.getProcessInfo(QName.valueOf(pid)).getDefinitionInfo().getDefinition()
                .getExtraElement().toString();

        BPELInterface bpel = new BPELImpl();
        //Converts the bpel process definition to an omElement which is how the AXIS2 Object Model (AXIOM)
        // represents an XML document
        OMElement bpelStr = bpel.load(processDef);
        /**
         * Process the OmElement containing the bpel process definition
         * Process the subactivites of the bpel process by iterating through the omElement
         * */
        bpel.processBpelString(bpelStr);

        //Create a new instance of the LayoutManager for the bpel process
        LayoutManager layoutManager = BPEL2SVGFactory.getInstance().getLayoutManager();
        //Set the layout of the SVG to vertical
        layoutManager.setVerticalLayout(true);
        //Get the root activity i.e. the Process Activity
        layoutManager.layoutSVG(bpel.getRootActivity());

        svg = new SVGImpl();
        //Set the root activity of the SVG i.e. the Process Activity
        svg.setRootActivity(bpel.getRootActivity());
        //Set the content type of the HTTP response as "image/png"
        response.setContentType("image/png");
        //Create an instance of ServletOutputStream to write the output
        ServletOutputStream sos = response.getOutputStream();
        //Convert the image as a byte array of a PNG
        byte[] pngBytes = svg.toPNGBytes();
        // stream to write binary data into the response
        sos.write(pngBytes);
        sos.flush();
        sos.close();

    } catch (ProcessManagementException e) {
        log.error("PNG Generation Error", e);
    }

}