Example usage for javax.servlet.http HttpServletRequest getInputStream

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

Introduction

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

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:com.wx.CustomerWXServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  ww  w .j a  v a2  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 {
    String sToken = "testToken";
    String sCorpID = "wxe706b25abb1216c0";
    String sEncodingAESKey = "AWdjbue1y51jzlAMwBCSm9GDt7zW6zuIbNqGEPcqsRR";
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    String msg_signature = request.getParameter("msg_signature");
    String timestamp = request.getParameter("timestamp");
    String nonce = request.getParameter("nonce");
    InputStream inputStream = request.getInputStream();
    String postData = IOUtils.toString(inputStream, "UTF-8");
    System.out.println(postData);
    String msg = "";
    WXBizMsgCrypt wxcpt = null;
    try {
        wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        //?
        msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData);
    } catch (AesException e) {
        e.printStackTrace();
    }
    System.out.println("msg=" + msg);
    BaseMessage respMessage = CoreService.processRequest(msg, classService);
    String resMsg = null;
    /** if (request.getSession().getAttribute("accessToken") == null) {
    try {
        String accessToken = CoreService.getAccessToken(config.getInitParameter("corpid"), config.getInitParameter("corpsecret"));
        request.getSession().setAttribute("accessToken", accessToken);
        QyWxURLUtil.applyAccessToken(accessToken);
    } catch (Exception ex) {
        Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
     }
     **/
    /**
     * UploadMediaReturnMessage uploadMediaReturnMsg; try {
     * uploadMediaReturnMsg = WXUtils.send("image",
     * "/root/WXMedia/anranhui520/1.jpg");
     * if("null".equals(uploadMediaReturnMsg.getErrcode())){
     * System.out.println("Media_id:"+uploadMediaReturnMsg.getMedia_id());
     * }else{ System.out.println("Upload error
     * message:"+uploadMediaReturnMsg.getErrmsg()+" error
     * code:"+uploadMediaReturnMsg.getErrcode());
     *
     * }
     * } catch (Exception ex) {
     * Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE,
     * null, ex); }
    *
     */
    if (respMessage instanceof TextMessage) {
        /*try {
        TextMessage txtMsg = (TextMessage) respMessage;
                
        String command = txtMsg.getContent();
                
        CheckCommandReturnMessage ccReturnMsg = CMDService.processCheckingCommand(command);
        Set<UserInfo> userInfoSet = ccReturnMsg.getUserInfos();
        UserInfo userif = null;
        for (UserInfo userInfo : userInfoSet) {
            userif = userInfo;
        }
                
        System.out.println("msgContent:" + ccReturnMsg.getContent());
        System.out.println("weixinid:" + userif.getWeixinid());
                
        try {
                
            UploadMediaReturnMessage uploadMediaReturnMsg = null;
            try {
                QRCodeGenerator.encode(ccReturnMsg.getContent(), "/root/WXMedia/"+userif.getWeixinid());
                        
                uploadMediaReturnMsg = WXUtils.send("image", "/root/WXMedia/"+userif.getWeixinid()+"/qrcode.jpg");
                if ("null".equals(uploadMediaReturnMsg.getErrcode())) {
                    System.out.println("Media_id:" + uploadMediaReturnMsg.getMedia_id());
                } else {
                    System.out.println("Upload error message:" + uploadMediaReturnMsg.getErrmsg() + " error code:" + uploadMediaReturnMsg.getErrcode());
                
                }
            } catch (Exception ex) {
                Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
            }*/

        /**
         * TextSendMessage textMsg = new TextSendMessage(); String
         * msgtxt = ccReturnMsg.getContent();
         * textMsg.setTextContent(msgtxt);
         * textMsg.setMsgtype("text");
         * textMsg.setTouser(userif.getWeixinid());
         * textMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); *
         */
        /*  ImageSendMessage imgMsg = new ImageSendMessage();
          imgMsg.setImageMedia(uploadMediaReturnMsg.getMedia_id());
          imgMsg.setMsgtype("image");
          imgMsg.setTouser(userif.getWeixinid());
          imgMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId")));
                
          AccessTokenReturnMessage returnMsg = CoreService.sendMessage(imgMsg);
        } catch (Exception ex) {
          Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        } catch (Exception ex) {
        Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    } else if (respMessage instanceof NewsMessage) {
        System.out.println("enter NewsMessage.");
        NewsMessage newsMsg = (NewsMessage) respMessage;
        resMsg = MessageUtil.newsMessageToXml(newsMsg);
        System.out.println("ResMsg:" + resMsg);
    }
    PrintWriter out = response.getWriter();
    out.print(resMsg);
    out.flush();
    out.close();

}

From source file:com.thoughtworks.go.server.controller.ArtifactsController.java

@RequestMapping(value = "/repository/restful/artifact/PUT/*", method = RequestMethod.PUT)
public ModelAndView putArtifact(@RequestParam("pipelineName") String pipelineName,
        @RequestParam("pipelineCounter") String pipelineCounter, @RequestParam("stageName") String stageName,
        @RequestParam(value = "stageCounter", required = false) String stageCounter,
        @RequestParam("buildName") String buildName,
        @RequestParam(value = "buildId", required = false) Long buildId,
        @RequestParam("filePath") String filePath,
        @RequestParam(value = "agentId", required = false) String agentId, HttpServletRequest request)
        throws Exception {
    if (filePath.contains("..")) {
        return FileModelAndView.forbiddenUrl(filePath);
    }/*  www . j a v  a2 s .  c om*/

    JobIdentifier jobIdentifier;
    try {
        jobIdentifier = restfulService.findJob(pipelineName, pipelineCounter, stageName, stageCounter,
                buildName, buildId);
    } catch (Exception e) {
        return buildNotFound(pipelineName, pipelineCounter, stageName, stageCounter, buildName);
    }

    if (isConsoleOutput(filePath)) {
        return putConsoleOutput(jobIdentifier, request.getInputStream());
    } else {
        return putArtifact(jobIdentifier, filePath, request.getInputStream());
    }
}

From source file:com.thinkberg.webdav.PropPatchHandler.java

/**
 * Handle a PROPPATCH request./*w  w  w.j a  va2  s. c o m*/
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        SAXReader saxReader = new SAXReader();
        try {
            Document propDoc = saxReader.read(request.getInputStream());
            logXml(propDoc);

            Element propUpdateEl = propDoc.getRootElement();
            List<Element> requestedProperties = new ArrayList<Element>();
            for (Object elObject : propUpdateEl.elements()) {
                Element el = (Element) elObject;
                String command = el.getName();
                if (AbstractDavResource.TAG_PROP_SET.equals(command)
                        || AbstractDavResource.TAG_PROP_REMOVE.equals(command)) {
                    for (Object propElObject : el.elements()) {
                        for (Object propNameElObject : ((Element) propElObject).elements()) {
                            Element propNameEl = (Element) propNameElObject;
                            requestedProperties.add(propNameEl);
                        }
                    }
                }
            }

            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusResponse(object, requestedProperties,
                    getBaseUrl(request));

            logXml(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            writer.flush();
            writer.close();

        } catch (DocumentException e) {
            LOG.error("invalid request: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        LOG.error(object.getName().getPath() + " NOT FOUND");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom PUT by calling handler to identify URI, reading/parsing
 * data, calling handler and writing results to response.
 *//* ww  w . j  a  v a  2  s  .c o  m*/
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isEntryURI(areq)) {

                // parse incoming entry
                Entry unsavedEntry = Atom10Parser.parseEntry(
                        new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null);

                // call handler to put entry
                handler.putEntry(areq, unsavedEntry);

                res.setStatus(HttpServletResponse.SC_OK);

            } else if (handler.isMediaEditURI(areq)) {

                // hand input stream to handler
                handler.putMedia(areq);

                res.setStatus(HttpServletResponse.SC_OK);

            } else {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing PUT", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing PUT", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        // Wanted to use sendError() here but Tomcat sends 403 forbidden 
        // when I do that, so sticking with setStatus() for time being.
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java

/**
 * @param request//from  w  w w  . j  av a 2s  . co  m
 * @return
 */
private HttpMethod buildRequest(final HttpServletRequest request, final URLResult urlResult) {
    final String method = request.getMethod().toUpperCase();
    final HttpMethod ret;

    final String uri = urlResult.getURL().toExternalForm();
    if ("GET".equals(method)) {
        ret = new GetMethod(uri);
        proxyHeaders(request, ret);
    } else if ("POST".equals(method) || "PUT".equals(method)) {
        final EntityEnclosingMethod pm = "POST".equals(method) ? new PostMethod(uri) : new PutMethod(uri);
        proxyHeaders(request, pm);
        try {
            pm.setRequestEntity(new InputStreamRequestEntity(request.getInputStream()));
        } catch (IOException e) {
            throw new UnhandledException("No pudo abrirse el InputStream" + "del request.", e);
        }
        ret = pm;

    } else if ("DELETE".equals(method)) {
        /*
        rfc2616
        The Content-Length field of a request or response is added or deleted
        according to the rules in section 4.4. A transparent proxy MUST
        preserve the entity-length (section 7.2.2) of the entity-body,
        although it MAY change the transfer-length (section 4.4).
        */
        final DeleteMethod dm = new DeleteMethod(uri);
        proxyHeaders(request, dm);
        //No body => No Header
        dm.removeRequestHeader("Content-Length");
        ret = dm;
    } else {
        throw new NotImplementedException("i accept patches :)");
    }

    if (request.getQueryString() != null) {
        ret.setQueryString(request.getQueryString());
    }

    return ret;
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();// w w w.  java  2 s .c o m
    addRemoteIpToLoggingContext(req);

    log.info("Handling autodiscover request...");

    byte[] reqBytes = null;
    reqBytes = ByteUtil.getContent(req.getInputStream(), req.getContentLength());
    if (reqBytes == null) {
        log.warn("No content found in the request");
        sendError(resp, 600, "No content found in the request");
        return;
    }
    String content = new String(reqBytes, "UTF-8");
    log.debug("Request before auth: %s", content);

    if (log.isDebugEnabled()) {
        Enumeration<String> enm = req.getHeaderNames();
        while (enm.hasMoreElements()) {
            String header = enm.nextElement();
            log.info("POST header: %s", header + ":" + req.getHeader(header));
        }
    }

    String email = null;
    String responseSchema = null;

    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(content)));
        NodeList nList = doc.getElementsByTagName("Request");

        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                email = getTagValue("EMailAddress", element);
                responseSchema = getTagValue("AcceptableResponseSchema", element);

                if (email != null)
                    break;
            }
        }
    } catch (Exception e) {
        log.warn("cannot parse body: %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Body cannot be parsed");
        return;
    }

    //Return an error if there's no email address specified!
    if (email == null || email.length() == 0) {
        log.warn("No Email address is specified in the Request, %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "No Email address is specified in the Request");
        return;
    }

    //Return an error if the response schema doesn't match ours!
    if (responseSchema != null && responseSchema.length() > 0) {

        if (!(responseSchema.equals(NS_MOBILE) || responseSchema.equals(NS_OUTLOOK))) {
            log.warn("Requested response schema not available " + responseSchema);
            sendError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "Requested response schema not available " + responseSchema);
            return;
        }
    }

    log.debug("Authenticating user");
    Account acct = authenticate(req, resp, responseSchema);
    if (acct == null) {
        return;
    }
    log.debug("Authentication finished successfully");

    log.debug("content length: %d, content type: %s", req.getContentLength(), req.getContentType());
    if (req.getContentLength() == 0 || req.getContentType() == null) {
        log.warn("No suitable content found in the request");
        sendError(resp, 600, "No suitable content found in the request");
        return;
    }

    try {
        if (!(AccountUtil.addressMatchesAccount(acct, email) || acct.isAvailabilityServiceProvider())) { //Exchange server sends dummy email address from service account.
            log.warn(email + " doesn't match account addresses for user " + acct.getName());
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    email + " doesn't match account addresses");
            return;
        }
    } catch (ServiceException e) {
        log.warn("Account access error; user=" + acct.getName(), e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Account access error; user=" + acct.getName());
        return;
    }

    String respDoc = null;
    try {
        String serviceUrl = getServiceUrl(acct, responseSchema);
        String displayName = acct.getDisplayName() == null ? email : acct.getDisplayName();
        if (displayName.contains("@")) {
            displayName = displayName.substring(0, displayName.indexOf("@"));
        }
        log.debug("displayName: %s, email: %s, serviceUrl: %s", displayName, email, serviceUrl);
        if (isEwsClient(responseSchema)) {
            respDoc = createResponseDocForEws(displayName, email, serviceUrl, acct);
        } else {
            respDoc = createResponseDoc(displayName, email, serviceUrl);
        }
    } catch (Exception e) {
        log.warn(e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.info("Response: %s", respDoc);
    log.debug("response length: %d", respDoc.length());

    try {
        ByteUtil.copy(new ByteArrayInputStream(respDoc.getBytes("UTF-8")), true, resp.getOutputStream(), false);
    } catch (IOException e) {
        log.error("copy response error", e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.debug("setting content type to text/xml");
    resp.setContentType("text/xml");
    log.info("sending autodiscover response...");
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

private HttpRequest newProxyRequest(final HttpServletRequest servletRequest, final String proxyRequestUri)
        throws IOException {
    final String method = servletRequest.getMethod();
    if (null != servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH)
            || null != servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING)) {
        //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
        final HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        r.setEntity(new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        return r;
    } else {//  ww w. j a  va2s .co  m
        return new BasicHttpRequest(method, proxyRequestUri);
    }
}

From source file:com.riq.MailHandlerServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)

        throws IOException {

    log.info("Inside MailServlet doPost");

    // TODO get path information to determine target Department for this email

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {//  w  w  w  .  j av a  2s .com

        MimeMessage msg = new MimeMessage(session, req.getInputStream());
        Address sender = msg.getFrom()[0];
        Address replyTo = msg.getReplyTo()[0];

        //      DEBUG
        //       log.info("Message Class: " + msg.getClass());
        //       log.info("Message Stream: " + msg.getInputStream());
        //       log.info("Message RawStream: " + msg.getRawInputStream());
        //       log.info("Message Flags: " + msg.getFlags());
        //       log.info("Message Content: " + msg.getContent().toString());
        //       log.info("Message ContentID: " + msg.getContentID());
        //       log.info("Message ContentMD: " + msg.getContentMD5());
        //       log.info("Message ContentType: " + msg.getContentType());
        //       log.info("Message Description: " + msg.getDescription());
        //       log.info("Message Disposition: " + msg.getDisposition());
        //       log.info("Message Encoding: " + msg.getEncoding());
        //       log.info("Message Filename: " + msg.getFileName());
        //       log.info("Message Line Count: " + msg.getLineCount());
        //       log.info("Message ID: " + msg.getMessageID());
        //       log.info("Message Number: " + msg.getMessageNumber());
        //       log.info("Message Size: " + msg.getSize());
        //       log.info("Message Subject: " + msg.getSubject());
        //       log.info("Message RawInputStream: " + msg.getRawInputStream().toString());
        //       log.info("Message ReplyTo: " + replyTo);
        //       log.info("Message Sender: " + sender.toString());
        //       log.info("Request URL TO: " +  getServletContext());      

        String alertMsgString = getText(msg);

        alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", "");
        alertMsgString = alertMsgString.replaceAll("Forwarded message", "");
        alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", "");
        alertMsgString = alertMsgString.replaceAll("Date:", "");
        alertMsgString = alertMsgString.replaceAll(">", "");
        alertMsgString = alertMsgString.replaceAll("::", "-");
        alertMsgString = alertMsgString.replaceAll("< ", "");
        alertMsgString = alertMsgString.replaceAll("----------", "");
        alertMsgString = alertMsgString.replaceAll("Subject:", "");
        alertMsgString = alertMsgString.replaceAll("To:", "");
        alertMsgString = alertMsgString.replaceAll("From:", "");

        //  Added to grab gmail confirmations
        //  alertMsgString = alertMsgString.substring(50, 300);

        try {

            String queryDept = "select from " + Department.class.getName() +
            // TODO: johnreilly workaround for getting allRecipients... 
            // " where dispatchId == '" + toAddressDigitsOnly + "' " + 
                    " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' ";
            log.info("queryDept: " + queryDept);
            List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute();

            if (depts.size() != 0) {

                for (Department d : depts) {

                    // need to filter further e.g. last two hours
                    String queryAlert = "select from " + Alert.class.getName() + " where deptId == "
                            + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' ";
                    log.info("queryAlert: " + queryAlert);
                    List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute();
                    log.info("queryAlert Result Qty: " + alerts.size());

                    if (alerts.size() == 0) {

                        riqGeocode(alertMsgString);

                        // geocode the address from the Alert
                        Map<String, String> geoResults = riqGeocode(alertMsgString);
                        log.info("lat print: " + geoResults.get("lat"));
                        log.info("lng print: " + geoResults.get("lng"));

                        // create the alert
                        Long deptId = depts.get(0).getid();
                        Long timeStamp = System.currentTimeMillis();
                        Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(),
                                "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID());
                        pm.makePersistent(a);

                        // query to get id of this alert
                        String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == "
                                + deptId + " " + " && timeStamp == " + timeStamp;
                        log.info("queryThisAlert: " + queryThisAlert);
                        List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute();
                        log.info("queryCurrentAlert Result Qty: " + thisAlert.size());

                        // create Tracking records for "special" Locations
                        String querySpecialLocs = "select from " + Location.class.getName()
                                + " where special == 'yes' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + querySpecialLocs);
                        List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute();
                        log.info("querySpecialLocs qty: " + specialLocs.size());

                        for (Location specL : specialLocs) {
                            Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(),
                                    System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                    "location", specL.getid(), null, "autoAddLocation");
                            pm.makePersistent(tSL);
                        }

                        // search Dept for Location where distant Members presumed not to be responding are set
                        String queryFarawayLocs = "select from " + Location.class.getName()
                                + " where vru == '2' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + queryFarawayLocs);
                        List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute();
                        log.info("queryFarawayLocs qty: " + farawayLoc.size());

                        // create Tracking records for Members presumed not to be responder due to fresh ETA
                        String queryFarAwayResponders = "select from " + Member.class.getName()
                                + " where distGroup == '4' ";
                        log.info("queryFarAwayResponders: " + queryFarAwayResponders);
                        List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders)
                                .execute();
                        log.info("queryFarAwayResponders qty: " + farawayMembers.size());

                        if (farawayMembers.size() != 0) {
                            for (Member far : farawayMembers) {
                                Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(),
                                        farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                        "farawayAddMember", far.getid(), null, responseType);
                                pm.makePersistent(tMFAR);
                            }
                        }

                        // TODO: testing restriction HACKER - remove at launch
                        // send alert email
                        String queryMember = "select from " + Member.class.getName() + " where deptId == "
                                + deptId + " && type == 'Hacker' ";
                        List<Member> members = (List<Member>) pm.newQuery(queryMember).execute();

                        //TODO Geocode address to insure easy navigation
                        //TODO johnreilly: add street and town fields to Alert
                        msg.setFrom(
                                new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder"));
                        msg.setSubject("Alert!");
                        msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() +
                        // "&3=" + d.getinboundVRU3() +  
                                "&A=" + thisAlert.get(0).getalertMsgString());

                        // send message to all dept members who permit tracking (and sending email alerts)
                        for (Member m : members) {
                            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(),
                                    m.getfirstName() + "" + m.getlastName()));
                            log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName());
                        }
                    }
                    // only process for one department - should only be one department
                    break;
                }
            }
        } catch (MessagingException me) {
            log.info("Error: Messaging");
        } catch (IndexOutOfBoundsException mi) {
            log.info("Error: Out of Bounds");
        }

        // Do not send alert notification if email is a Google Confirmation
        //      if (! sender.toString().contains("mail-noreply@google.com")) {
        //        Transport.send(msg);
        //      }

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } finally {
        pm.close();
    }

}

From source file:com.wdeanmedical.portal.service.AppService.java

public String uploadProfileImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String patientId = request.getParameter("patientId");
    InputStream is = null;//w w  w  . ja  v a 2  s  . c om
    FileOutputStream fos = null;
    String returnString = "";

    is = request.getInputStream();
    String filename = request.getHeader("X-File-Name");
    String filesHomePatientDirPath = Core.filesHome + Core.patientDirPath + "/" + patientId + "/";
    fos = new FileOutputStream(new File(filesHomePatientDirPath + filename));
    IOUtils.copy(is, fos);
    response.setStatus(HttpServletResponse.SC_OK);
    fos.close();
    is.close();

    String[] imageMagickArgs = { Core.imageMagickHome + "convert", filesHomePatientDirPath + filename,
            "-resize", "160x160", filesHomePatientDirPath + filename };
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(imageMagickArgs);

    InputStream pis = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(pis);
    BufferedReader br = new BufferedReader(isr);
    String line;
    log.info("Output of running " + Arrays.toString(imageMagickArgs) + "is: ");

    while ((line = br.readLine()) != null) {
        log.info(line);
    }
    log.info("\n" + filename + " uploaded");

    Patient patient = appDAO.findPatientById(new Integer(patientId));
    appDAO.updatePatientProfileImage(patient, filename);

    returnString = "{\"filename\":\"" + filename + "\"}";
    activityLogService.logViewPatient(patient.getId(), null, patient.getId(), "UploadProfileImage");
    return returnString;
}