Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getUserPrincipal.

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/restartAllBatchInstance", method = RequestMethod.GET)
@ResponseBody/*from ww  w . j  a v a2 s . com*/
public String restartAllBatchInstance(final HttpServletResponse resp, final HttpServletRequest req) {
    String isSuccess = WebServiceUtil.EMPTY_STRING;
    String userName = req.getUserPrincipal().getName(); // ToDo fetch from authentication header.
    Set<String> userRoles = userConnectivityService.getUserGroups(userName);
    List<BatchInstanceStatus> batchStatusList = new ArrayList<BatchInstanceStatus>();
    batchStatusList.add(BatchInstanceStatus.READY_FOR_REVIEW);
    batchStatusList.add(BatchInstanceStatus.READY_FOR_VALIDATION);
    List<BatchInstance> batchInstanceList = biService.getBatchInstanceByStatusList(batchStatusList);
    final boolean isZipSwitchOn = bsService.isZipSwitchOn();
    if (batchInstanceList.size() > 0) {
        for (BatchInstance batchInstance : batchInstanceList) {
            Set<String> batchInstanceRoles = biService.getRolesForBatchInstance(batchInstance);
            String batchInstanceIdentifier = batchInstance.getIdentifier();
            logger.info("Restarting batch instance : " + batchInstanceIdentifier);
            if (batchInstanceRoles.removeAll(userRoles)) {
                String activityName = workflowService.getActiveModule(batchInstance);
                if (activityName != null) {
                    int indexOf = activityName.indexOf('.');
                    indexOf = indexOf == -1 ? activityName.length() : indexOf;
                    String moduleName = activityName.substring(0, indexOf);
                    try {
                        String batchClassIdentifier = biService
                                .getBatchClassIdentifier(batchInstanceIdentifier);
                        isSuccess = processRestartingBatchInternal(batchInstanceIdentifier, moduleName,
                                isSuccess.toString(), batchInstance, batchClassIdentifier, isZipSwitchOn,
                                activityName);
                    } catch (Exception e) {
                        if (isSuccess.isEmpty()) {
                            isSuccess += "Error in restarting following batch instance identifiers: ";
                        } else {
                            isSuccess += ", ";
                        }
                        isSuccess += batchInstanceIdentifier;
                        logger.error("Error while restarting batch instance: " + batchInstanceIdentifier);
                    }
                } else {
                    if (isSuccess.isEmpty()) {
                        isSuccess += "Error in restarting batch instance identifiers are : ";
                    } else {
                        isSuccess += ", ";
                    }
                    isSuccess += batchInstanceIdentifier;
                }
            } else {
                if (isSuccess.isEmpty()) {
                    isSuccess += "Error in restarting following batch instance identifiers:";
                } else {
                    isSuccess += ", ";
                }
                isSuccess += "User is not authorized for id:" + batchInstanceIdentifier;
                logger.error("Error while restarting batch instance: " + batchInstanceIdentifier);
            }
        }

    } else {
        isSuccess = "No results found.";
    }
    return isSuccess;
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/restartBatchInstance/{batchInstanceIdentifier}/{restartAtModuleName}", method = RequestMethod.GET)
@ResponseBody/*from   w ww.j av a  2s . c  o m*/
public String restartBatchInstance(@PathVariable("batchInstanceIdentifier") final String identifier,
        @PathVariable("restartAtModuleName") String moduleName, final HttpServletResponse resp,
        final HttpServletRequest req) {
    logger.info("Start processing web service for restart batch instance");
    boolean isSuccess = false;
    String userName = req.getUserPrincipal().getName(); // ToDo fetch from authentication header.
    Set<String> userRoles = userConnectivityService.getUserGroups(userName);
    String respStr = WebServiceUtil.EMPTY_STRING;
    if (identifier != null && !identifier.isEmpty()) {
        BatchInstance batchInstance = biService.getBatchInstanceByIdentifier(identifier);
        // only batch instance with these status can be restarted
        if (batchInstance != null && (batchInstance.getStatus().equals(BatchInstanceStatus.ERROR)
                || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_REVIEW)
                || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_VALIDATION)
                || batchInstance.getStatus().equals(BatchInstanceStatus.RUNNING))) {

            Set<String> batchInstanceRoles = biService.getRolesForBatchInstance(batchInstance);
            if (batchInstanceRoles.removeAll(userRoles)) {
                String executedBatchInstanceModules = batchInstance.getExecutedModules();
                String[] executedModulesArray = executedBatchInstanceModules.split(";");
                final String batchClassIdentifier = biService.getBatchClassIdentifier(identifier);
                if (batchClassIdentifier != null) {
                    final BatchClassModule batchClassModuleItem = bcModuleService
                            .getBatchClassModuleByWorkflowName(batchClassIdentifier, moduleName);
                    if (batchClassModuleItem != null) {
                        for (String string : executedModulesArray) {
                            if (string.equalsIgnoreCase(String.valueOf(batchClassModuleItem.getId()))) {
                                isSuccess = true;
                                break;
                            }
                        }
                    }

                }
                final boolean isZipSwitchOn = bsService.isZipSwitchOn();
                logger.info("Zipped Batch XML switch is:" + isZipSwitchOn);

                final String activeModule = workflowService.getActiveModule(batchInstance);

                if (isSuccess) {
                    respStr = processRestartingBatchInternal(identifier, moduleName, respStr, batchInstance,
                            batchClassIdentifier, isZipSwitchOn, activeModule);
                } else {
                    isSuccess = false;
                    respStr = "Invalid parameter for restarting batch instance.";
                }
            } else {
                respStr = "User is not authorized to perform operation on this batch instance." + identifier;
            }
        } else {
            respStr = "Either Batch instance does not exist with batch instance identifier " + identifier
                    + " or batch exists with incorrect status to be restarted. Batch instance should be of status:-"
                    + "ERROR, READY_FOR_REVIEW, READY_FOR_VALIDATION, RUNNING";
            isSuccess = false;
        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {
        }
    }
    return (isSuccess ? "Batch restarted successfully." : "Failure while restarting batch instance.");
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/deleteBatchInstance/{identifier}", method = RequestMethod.GET)
@ResponseBody/* w  w w.  j av a2s  .com*/
public String deleteBatchInstance(@PathVariable("identifier") final String identifier,
        final HttpServletResponse resp, final HttpServletRequest req) {
    logger.info("Start processing web service for delete batch instance");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String userName = req.getUserPrincipal().getName(); // ToDo fetch from authentication header.
    Set<String> userRoles = userConnectivityService.getUserGroups(userName);
    boolean isSuccess = false;
    if (identifier != null && !identifier.isEmpty()) {
        final BatchInstance batchInstance = biService.getBatchInstanceByIdentifier(identifier);
        try {
            // Status for which a batch can be deleted:
            if (batchInstance != null && (batchInstance.getStatus().equals(BatchInstanceStatus.ERROR)
                    || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_REVIEW)
                    || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_VALIDATION)
                    || batchInstance.getStatus().equals(BatchInstanceStatus.RUNNING))) {

                Set<String> batchInstanceRoles = biService.getRolesForBatchInstance(batchInstance);
                if (batchInstanceRoles.removeAll(userRoles)) {
                    pluginPropertiesService.clearCache(identifier);
                    jbpmService.deleteProcessInstance(batchInstance.getProcessInstanceKey());
                    batchInstance.setStatus(BatchInstanceStatus.DELETED);
                    biService.updateBatchInstance(batchInstance);
                    final File uncFile = new File(batchInstance.getUncSubfolder());
                    if (null != uncFile) {
                        FileUtils.deleteDirectoryAndContentsRecursive(uncFile);
                    }
                    isSuccess = true;
                } else {
                    respStr = "User is not authorized to perform operation on this batch instance."
                            + identifier;
                }
            } else {
                respStr = "Either Batch instance does not exist with batch instance identifier " + identifier
                        + " or batch exists with incorrect status to be deleted. Batch instance should be of status:-"
                        + "ERROR, READY_FOR_REVIEW, READY_FOR_VALIDATION, RUNNING";
            }
        } catch (final Exception e) {
            respStr = "Error while deleting batch instance id:" + identifier
                    + ".Please check logs for further details." + e;

        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
    return (isSuccess ? "Batch deleted successfully." : "Failure while deleting batch instance.");
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/getBatchClassList", method = RequestMethod.GET)
@ResponseBody//  w  w w. j  a v a 2 s . c o m
public void getBatchClassList(final HttpServletResponse resp, final HttpServletRequest req) {
    logger.info("Start processing web service for get batch class list");
    logger.info("Fetching batch class from the database");
    String userName = req.getUserPrincipal().getName(); // ToDo fetch from authentication header.
    Set<String> userRoles = userConnectivityService.getUserGroups(userName);
    if (userRoles == null || userRoles.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "User not authorized to view this API.");
        } catch (final IOException ioe) {

        }
    } else {
        final List<BatchClass> batchClass = bcService.getAllBatchClassesByUserRoles(userRoles);
        final BatchClasses batchClasses = new BatchClasses();
        final List<com.ephesoft.dcma.batch.schema.BatchClasses.BatchClass> batchClassList = batchClasses
                .getBatchClass();
        logger.info("Total batch class found from the database is : " + batchClass.size());
        for (final BatchClass eachBatchClass : batchClass) {
            final com.ephesoft.dcma.batch.schema.BatchClasses.BatchClass batchClassLocal = new com.ephesoft.dcma.batch.schema.BatchClasses.BatchClass();
            batchClassLocal.setCurrentUser(eachBatchClass.getCurrentUser());
            batchClassLocal.setDescription(eachBatchClass.getDescription());
            batchClassLocal.setIdentifier(eachBatchClass.getIdentifier());
            batchClassLocal.setIsDeleted(eachBatchClass.isDeleted());
            batchClassLocal.setName(eachBatchClass.getName());
            batchClassLocal.setPriority(eachBatchClass.getPriority());
            batchClassLocal.setUncFolder(eachBatchClass.getUncFolder());
            batchClassLocal.setVersion(eachBatchClass.getVersion());
            batchClassList.add(batchClassLocal);

        }
        StreamResult result;
        try {
            result = new StreamResult(resp.getOutputStream());
            resp.setStatus(HttpServletResponse.SC_OK);
            batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(batchClasses, result);
        } catch (final IOException e) {
            try {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal Server error.Please check logs for further details." + e.getMessage());
            } catch (final IOException ioe) {

            }
        }
    }
}

From source file:de.jwi.jfm.servlets.Controller.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String self = null;// w w w . j  av a2 s .  co  m
    String contextPath = null;
    String pathInfo = null;
    Folder folder = null;
    String queryString = null;

    try {
        contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String method = request.getMethod();
        boolean formPosted = "POST".equals(method);

        pathInfo = request.getPathInfo();

        if (null == pathInfo) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + servletPath + " is alive.");

            return;
        }

        File f = new File(filebase, pathInfo);

        if (!f.exists()) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + pathInfo + " does not exist.");

            return;
        }

        if (f.isFile()) {
            doDownload(request, response, f);
            return;
        }

        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(request.getRequestURL() + "/");
            return;
        }

        queryString = request.getQueryString();

        String pathTranslated = request.getPathTranslated();
        String requestURI = request.getRequestURI();
        String requestURL = request.getRequestURL().toString();

        self = contextPath + servletPath;

        String fileURL = requestURI.replaceFirst(contextPath, "");
        fileURL = fileURL.replaceFirst(servletPath, "");

        folder = new Folder(f, pathInfo, fileURL);

        folder.load();

        String actionresult = "";

        if (FileUpload.isMultipartContent(request)) {
            try {
                actionresult = handleUpload(request, folder);
                folder.load();
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else if (formPosted || null != queryString) {
            try {
                actionresult = handleQuery(request, response, folder);
            } catch (OutOfSyncException e) {
                actionresult = e.getMessage();
            }
            if (null == actionresult) {
                return;
            }
        }

        request.setAttribute("actionresult", actionresult);
    } catch (SecurityException e) {
        request.setAttribute("actionresult", e.getClass().getName() + " " + e.getMessage());
        request.setAttribute("fatalerror", new Boolean(true));

    }

    String s = request.getRemoteUser();

    Principal principal = request.getUserPrincipal();

    if (principal != null) {
        request.setAttribute("principal", principal.getName());
    }

    request.setAttribute("self", self);

    s = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z").format(new Date());

    request.setAttribute("date", s);

    request.setAttribute("version", version);

    request.setAttribute("builddate", builddate);

    request.setAttribute("javaversion", System.getProperty("java.version"));

    request.setAttribute("serverInfo", getServletContext().getServerInfo());

    request.setAttribute("jfmhome", "https://java.net/projects/jfm");

    request.setAttribute("url", contextPath);

    request.setAttribute("path", pathInfo);

    request.setAttribute("folder", folder);

    String forward = "/WEB-INF/fm.jsp";

    if (queryString != null) {
        // hide get query parameters
        //         response.sendRedirect(request.getRequestURL() + "");
        //         return;
    }

    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(forward);

    requestDispatcher.forward(request, response);
}

From source file:org.opencms.webdav.CmsWebdavServlet.java

/**
 * Generates a lock token out of the lock and some information out of the
 * request to make it unique.<p>//from  w w  w  . j  av a 2 s .com
 * 
 * @param req the servlet request we are processing
 * @param lock the lock with the information for the lock token
 * 
 * @return the generated lock token
 */
private String generateLockToken(HttpServletRequest req, CmsRepositoryLockInfo lock) {

    String lockTokenStr = req.getServletPath() + "-" + req.getUserPrincipal() + "-" + lock.getOwner() + "-"
            + lock.getPath() + "-" + m_secret;

    return MD5_ENCODER.encode(m_md5Helper.digest(lockTokenStr.getBytes()));
}

From source file:com.sg.rest.filters.LoggerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
        LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString());
        throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST);
    }//from  www.j  a  va 2 s .com

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    StringBuilder sb = new StringBuilder();
    //General header
    sb.append(System.lineSeparator());
    sb.append(INCOMING_REQUEST);
    //Request url
    sb.append(System.lineSeparator());
    sb.append(REQUEST_URL);
    sb.append(httpRequest.getRequestURL());
    //Method
    sb.append(System.lineSeparator());
    sb.append(METHOD);
    sb.append(httpRequest.getMethod());
    //Parameters
    if (httpRequest.getParameterNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(PARAMETERS);
        Enumeration enParams = httpRequest.getParameterNames();
        while (enParams.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String paramName = (String) enParams.nextElement();
            sb.append(paramName);
            sb.append(" : ");
            sb.append(httpRequest.getParameter(paramName));
        }
    }
    //Attributes
    if (httpRequest.getAttributeNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(ATTRIBUTES);
        Enumeration enAttribs = httpRequest.getAttributeNames();
        while (enAttribs.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String attribName = (String) enAttribs.nextElement();
            sb.append(attribName);
            sb.append(" : ");
            sb.append(httpRequest.getAttribute(attribName));
        }
    }
    //Headers
    if (httpRequest.getHeaderNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(HEADERS);
        Enumeration enHeaders = httpRequest.getHeaderNames();
        while (enHeaders.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String headerName = (String) enHeaders.nextElement();
            sb.append(headerName);
            sb.append(" : ");
            sb.append(httpRequest.getHeader(headerName));
        }
    }
    //AuthType
    if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(AUTH_TYPE);
        sb.append(httpRequest.getAuthType());
    }
    //Cookies
    if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) {
        sb.append(System.lineSeparator());
        sb.append(COOKIES);
        for (Cookie cookie : httpRequest.getCookies()) {
            sb.append(System.lineSeparator());
            sb.append(cookie.getName());
            sb.append(" : ");
            sb.append(cookie.getValue());
        }
    }
    //RemoteAddr
    if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_ADDR);
        sb.append(httpRequest.getRemoteAddr());
    }
    //RemoteHost
    if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_HOST);
        sb.append(httpRequest.getRemoteHost());
    }
    //User principal
    if (httpRequest.getUserPrincipal() != null) {
        if (httpRequest.getUserPrincipal().getName() != null
                && !httpRequest.getUserPrincipal().getName().isEmpty()) {
            sb.append(System.lineSeparator());
            sb.append(PRINCIPAL);
            sb.append(httpRequest.getUserPrincipal().getName());
        }
    }
    //Body
    ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
            (HttpServletRequest) request);
    String body = IOUtils.toString(wrappedRequest.getReader());
    if (body != null && !body.isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(BODY);
        sb.append(System.lineSeparator());
        sb.append(body);
    }
    wrappedRequest.resetInputStream();

    LOGGER.info(sb.toString());
    chain.doFilter(wrappedRequest, response);
}

From source file:org.georchestra.security.Proxy.java

/**
 * Main entry point for methods where the request path is encoded in the
 * path of the URL//from  ww w .j av a2 s. co m
 */
private void handlePathEncodedRequests(HttpServletRequest request, HttpServletResponse response,
        RequestType requestType) {
    try {
        String contextPath = request.getServletPath() + request.getContextPath();
        String forwardRequestURI = buildForwardRequestURL(request);

        logger.debug("handlePathEncodedRequests: -- Handling Request: " + requestType + ":" + forwardRequestURI
                + " from: " + request.getRemoteAddr());

        String sURL = findTarget(forwardRequestURI);

        if (sURL == null) {
            response.sendError(404);
            return;
        }

        URL url;
        try {
            url = new URL(sURL);
        } catch (MalformedURLException e) {
            throw new MalformedURLException(sURL + " is not a valid URL");
        }

        boolean sameHostAndPort = false;

        try {
            sameHostAndPort = isSameHostAndPort(request, url);
        } catch (UnknownHostException e) {
            logger.error("Unknown host in requested URL", e);
            response.sendError(503);
            return;
        }

        if (sameHostAndPort && (isRecursiveCallToProxy(forwardRequestURI, contextPath)
                || isRecursiveCallToProxy(url.getPath(), contextPath))) {
            response.sendError(403,
                    forwardRequestURI + " is a recursive call to this service.  That is not a legal request");
        }

        if (request.getQueryString() != null && !isFormContentType(request)) {
            StringBuilder query = new StringBuilder("?");
            Enumeration paramNames = request.getParameterNames();
            boolean needCasValidation = false;
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                String[] values = request.getParameterValues(name);
                for (String string : values) {
                    if (query.length() > 1) {
                        query.append('&');
                    }
                    // special case: if we have a ticket parameter and no
                    // authentication principal, we need to validate/open
                    // the session against CAS server
                    if ((request.getUserPrincipal() == null)
                            && (name.equals(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER))) {
                        needCasValidation = true;
                    } else {
                        query.append(name);
                        query.append('=');
                        query.append(URLEncoder.encode(string, "UTF-8"));
                    }
                }
            }
            sURL += query;
            if ((needCasValidation) && (urlIsProtected(request, new URL(sURL)))) {
                // loginUrl: sends a redirect to the client with a ?login (or &login if other arguments)
                // since .*login patterns are protected by the SP, this would trigger an authentication
                // onto CAS (which should succeed if the user is already connected onto the platform).
                String loginUrl = String.format("%s%s%s", request.getPathInfo(), query, "login");
                redirectStrategy.sendRedirect(request, response, loginUrl);
                return;
            }
        }

        handleRequest(request, response, requestType, sURL, true);
    } catch (IOException e) {
        logger.error("Error connecting to client", e);
    }
}

From source file:org.appcelerator.transport.UploadTransportServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getMethod().equalsIgnoreCase("POST")) {
        // paranoia check -we don't accept urlencoded transfers which are very bad performance wise
        if (false == ServletFileUpload.isMultipartContent(request)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "must be 'multipart/form-data'");
            return;
        }/*from  w w w. ja  va  2  s  .  com*/

        String type = null;
        String callback = null;
        long size = 0L;
        // String instanceid = null;
        IMessageDataObject data = MessageUtils.createMessageDataObject();

        try {
            ServletFileUpload upload = new ServletFileUpload(fileFactory);
            List items = upload.parseRequest(request);
            for (Iterator i = items.iterator(); i.hasNext();) {
                FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("callback")) {
                        callback = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("instanceid")) {
                        //instanceid = item.getString();
                        continue;
                    }
                    // place it in the data payload
                    data.put(item.getFieldName(), item.getString());
                } else {
                    File f = null;
                    if (tempDirectory != null) {
                        f = File.createTempFile("sup", ".tmp", tempDirectory);
                    } else {
                        f = File.createTempFile("sup", ".tmp");
                    }

                    f.deleteOnExit();

                    // write out the temporary file
                    item.write(f);

                    size = item.getSize();

                    IMessageDataObject filedata = MessageUtils.createMessageDataObject();

                    filedata.put("file", f.getAbsolutePath());
                    filedata.put("size", size);
                    filedata.put("contentType", item.getContentType());
                    filedata.put("fieldName", item.getFieldName());
                    filedata.put("fileName", item.getName());

                    data.put("filedata", filedata);
                }
            }

            // required parameter type
            if (type == null || type.equals("")) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing 'type' parameter");
                return;
            }
        } catch (Throwable fe) {
            fe.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fe.getMessage());
            return;
        }

        String scope = request.getParameter("scope");
        String version = request.getParameter("version");

        if (scope == null) {
            scope = "appcelerator";
        }
        if (version == null) {
            version = "1.0";
        }

        // create a message
        Message msg = new Message();
        msg.setUser(request.getUserPrincipal());
        msg.setSession(request.getSession());
        msg.setServletRequest(request);
        msg.setType(type);
        msg.setData(data);
        msg.setAddress(InetAddress.getByName(request.getRemoteAddr()));
        msg.setScope(scope);
        msg.setVersion(version);

        // send the data
        ArrayList<Message> responses = new ArrayList<Message>();
        try {
            ServiceRegistry.dispatch(msg, responses);
        } catch (Exception ex) {
            LOG.error("error dispatching upload message: " + msg, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
        response.setDateHeader("Expires", System.currentTimeMillis() - TimeUtil.ONE_YEAR);
        response.setContentType("text/html;charset=UTF-8");

        // optionally, invoke a callback function/message on upload in the client
        if (callback != null || !responses.isEmpty()) {
            StringBuilder code = new StringBuilder();
            code.append("<html><head><script>");

            if (callback != null) {
                if (callback.startsWith("l:") || callback.startsWith("local:") || callback.startsWith("r:")
                        || callback.startsWith("remote:")) {
                    code.append(makeMessage(callback, "{size:" + size + "}", scope, version));
                } else {
                    // a javascript function to call
                    code.append("window.parent.").append(callback).append("();");
                }
            }

            for (Message m : responses) {
                code.append(makeMessage(m.getType(), m.getData().toDataString(), m.getScope(), m.getVersion()));
            }

            code.append("</script></head><body></body></html>");

            // send the response
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print(code.toString());
        } else {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
        }
    } else {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "method was: " + request.getMethod());
    }
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/getBatchInstanceList/{status}/", method = RequestMethod.GET)
@ResponseBody//from w  w  w .j  a  va 2s  . c  o  m
public void getBatchInstanceList(@PathVariable("status") final String status, final HttpServletResponse resp,
        final HttpServletRequest req) {
    logger.info("Start processing get batch instance list from batch status web service");
    String respStr = WebServiceUtil.EMPTY_STRING;
    Set<String> batchInstancesId = null;
    if (!BatchInstanceStatus.valuesAsStringList().contains(status)) {
        respStr = "Invalid value for batch instance status. Please try again.";
    } else {
        final BatchInstanceStatus batchInstanceStatus = BatchInstanceStatus.valueOf(status);
        logger.info("Batch instance status is " + status);
        logger.info("Feteching batch instance list from the database");
        final List<BatchInstance> batchInstance = biService.getBatchInstByStatus(batchInstanceStatus);
        if (batchInstance != null && !batchInstance.isEmpty()) {
            String userName = req.getUserPrincipal().getName();
            Set<String> userRoles = userConnectivityService.getUserGroups(userName);

            // fetch the batch instances from batch instance groups
            batchInstancesId = batchInstanceGroupsService.getBatchInstanceIdentifierForUserRoles(userRoles);

            // fetch the list of batch instances from the batch instance table for batch classes having the given role.
            List<BatchClass> batchClasses = bcService.getAllBatchClassesByUserRoles(userRoles);
            for (BatchClass batchClass : batchClasses) {
                List<BatchInstance> eachBatchInstance = biService.getBatchInstByBatchClass(batchClass);
                for (BatchInstance bi : eachBatchInstance) {
                    batchInstancesId.add(bi.getIdentifier());
                }
            }

            final BatchInstances batchinstances = new BatchInstances();

            final List<com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance> batchInstanceList = batchinstances
                    .getBatchInstance();

            for (final BatchInstance eachBatchInstance : batchInstance) {
                if (batchInstancesId.contains(eachBatchInstance.getIdentifier())) {
                    final com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance batchLocal = new com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance();
                    batchLocal.setIdentifier(eachBatchInstance.getIdentifier());
                    batchLocal.setBatchName(eachBatchInstance.getBatchName());
                    batchLocal.setCurrentUser(eachBatchInstance.getCurrentUser());
                    batchLocal.setExecutedModules(eachBatchInstance.getExecutedModules());
                    batchLocal.setLocalFolder(eachBatchInstance.getLocalFolder());
                    batchLocal.setRemoteBatchInstanceId(eachBatchInstance.getRemoteBatchInstance() != null
                            ? eachBatchInstance.getRemoteBatchInstance().getRemoteBatchInstanceIdentifier()
                            : null);
                    batchLocal.setReviewOperatorName(eachBatchInstance.getReviewUserName());
                    batchLocal.setServerIP(eachBatchInstance.getServerIP());
                    batchLocal.setUncSubFolder(eachBatchInstance.getUncSubfolder());
                    batchLocal.setValidateOperatorName(eachBatchInstance.getValidationUserName());

                    batchInstanceList.add(batchLocal);
                }
            }
            StreamResult result;
            try {
                result = new StreamResult(resp.getOutputStream());
                resp.setStatus(HttpServletResponse.SC_OK);
                batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(batchinstances, result);
            } catch (final IOException e) {
                respStr = "Internal Server error.Please check logs for further details." + e;
            }
        } else {
            respStr = "No results found.";
        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}