Example usage for java.util.regex Matcher end

List of usage examples for java.util.regex Matcher end

Introduction

In this page you can find the example usage for java.util.regex Matcher end.

Prototype

public int end() 

Source Link

Document

Returns the offset after the last character matched.

Usage

From source file:com.adaptris.core.services.splitter.SimpleRegexpMessageSplitter.java

@Override
protected ArrayList<String> split(String messagePayload) throws Exception {
    String batch = messagePayload;
    compiledSplitPattern = compile(compiledSplitPattern, splitPattern);
    Matcher splitMatcher = compiledSplitPattern.matcher(batch);
    Matcher compareMatcher = null;
    if (compareToPreviousMatch()) {
        compiledMatchPattern = compile(compiledMatchPattern, matchPattern);
        compareMatcher = compiledMatchPattern.matcher(batch);
    }/*from   www. j  a va2s  .  c o  m*/

    ArrayList<String> splitMessages = new ArrayList();
    int splitStart = 0;
    int splitEnd = 0;
    StringBuffer currentSplitMsg = new StringBuffer();
    String currentMatch = null;
    if (compareToPreviousMatch()) {
        try {
            // do not check for a match first - we want to throw an exception if
            // no match found.
            compareMatcher.find(); // lgtm
            currentMatch = compareMatcher.group(1);
        } catch (Exception e) {
            throw new Exception("Could not match record comparator [" + e.getMessage() + "]", e);
        }
    }

    while (splitMatcher.find(splitEnd)) {
        splitEnd = splitMatcher.end();
        String thisRecord = batch.substring(splitStart, splitEnd);
        if (compareToPreviousMatch()) {
            compareMatcher = compiledMatchPattern.matcher(thisRecord);
            // We may get an empty line, in which case the compare.start() and
            // compare.end() methods will throw an IllegalStateException
            String newMatch = "";
            if (compareMatcher.find()) {
                newMatch = compareMatcher.group(1);
            }
            if (currentMatch.equals(newMatch)) { // lgtm
                // Still in the same message
                currentSplitMsg.append(thisRecord);
            } else {
                // The current thisRecord value is actually the start of the next
                // message, so we should store the last record and start again
                // with this one.
                splitMessages.add(currentSplitMsg.toString()); // ********
                currentSplitMsg.setLength(0);
                currentSplitMsg.append(thisRecord);
                currentMatch = newMatch;
            }
        } else {
            splitMessages.add(thisRecord);
        }
        splitStart = splitEnd;
    }
    // last message - might be an empty String
    String thisRecord = batch.substring(splitStart);
    if (compareToPreviousMatch()) {
        compareMatcher = compiledMatchPattern.matcher(thisRecord);
        // We may get an empty line, in which case the compare.start() and
        // compare.end() methods will throw an IllegalStateException
        String newMatch = "";
        if (compareMatcher.find()) {
            newMatch = compareMatcher.group(1);
        }
        if (currentMatch.equals(newMatch)) { // lgtm
            // Still in the same message
            currentSplitMsg.append(thisRecord);
            splitMessages.add(currentSplitMsg.toString());
        } else {
            // The current thisRecord value is actually the start of the next
            // message, so we should store the last record and start again
            // with this one.
            splitMessages.add(currentSplitMsg.toString());
            currentSplitMsg.setLength(0);
            // Must be a single line record - write it out (unless empty)
            if (thisRecord.trim().length() > 0) {
                splitMessages.add(thisRecord);
            }
        }
    } else {
        // Must be a single line record - write it out (unless empty)
        if (thisRecord.trim().length() > 0) {
            splitMessages.add(thisRecord);
        }
    }
    if (ignoreFirstSubMessage()) {
        splitMessages.remove(0);
    }
    return splitMessages;
}

From source file:edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalSubQuery.java

private String addToRegExExpression(String sqlString, String regEx, String newSql) {
    StringBuilder sql = new StringBuilder();
    Pattern p = Pattern.compile(regEx, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(sqlString);
    int lastIndex = 0;
    while (m.find()) {
        int endIndex = m.end();
        String text = sqlString.substring(lastIndex, endIndex - getSqlDelimiter().length());
        sql.append(text);//from   w w  w  . j ava2s  .  co  m
        sql.append(newSql);
        sql.append(getSqlDelimiter());
        lastIndex = endIndex;
    }
    sql.append(sqlString.substring(lastIndex));
    return sql.toString();
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

/**
 * Look for a session and if it's completed or not found try 
 *                            re-validate existing security token
 *///from  ww  w . j  av a2s. c  om
@Override
public void validate(HttpServletRequest req, String stoken) throws WsSrvException {
    Session session = activeSessions.get(stoken);

    if (!(session == null || session.isFinished()))
        // Everything fine
        return;

    getLogger(req).debug("Local session validation faied." + " Sending POST request to validate SAML session");

    // Revalidate session
    PostMethod post = new PostMethod(_login);

    try {
        String ars = createAuthnRequest(getServiceLocation(req), getRefererUrl(req));
        post.setParameter("SAMLRequest", ars);
    } catch (MarshallingException | SignatureException | IOException e) {
        //-- 63
        throw new WsSrvException(63, e);
    }

    HttpClient hc = (new HttpClientBuilder()).buildClient();
    post.setRequestHeader("Cookie",
            (String) req.getSession().getServletContext().getAttribute("scookie_name") + "=" + stoken);

    int result;
    try {
        result = hc.executeMethod(post);
    } catch (IOException e) {
        //-- 66
        throw new WsSrvException(66, e);
    }

    // Expecting 200 if cookie valid and 302 if not, rest are errors
    if (result == HttpStatus.SC_OK) {
        // Extract end process SAML response from form
        String rb;
        try {
            rb = new String(post.getResponseBody());
        } catch (IOException e) {
            //-- 67
            throw new WsSrvException(67, e);
        }

        Matcher m = SAML_RESP.matcher(rb);

        if (m.matches() && m.groupCount() == 1) {
            String gs = m.group(1);

            // Convert hex decoded javascript variable
            String msg = "";
            int start = 0;
            Matcher m1 = HP.matcher(gs);

            while (m1.find()) {
                String dc = m1.group(1);
                int i = Integer.decode("#" + dc);

                int st = m1.start();
                int ed = m1.end();

                msg += gs.substring(start, st) + (char) i;
                start = ed;
            }

            try {
                procAuthnResponse(req, msg, stoken);
            } catch (Exception e) {
                //-- 62
                throw new WsSrvException(62, e);
            }
        }
    } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
        //-- 64
        throw new WsSrvException(64, "Redirect received");
    } else {
        //-- 65
        throw new WsSrvException(65, "Unexpected http return code " + result);
    }
}

From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java

@RequestMapping(value = "/encounters", method = RequestMethod.GET)
@ResponseBody//from ww w.j a v  a 2 s  .c  om
public Object getEncounters(@RequestParam(value = "patientId", required = true) String patientId,
        @RequestParam(value = "idType", required = true) String idType,
        @RequestParam(value = "encounterUniqueId", required = false) String encounterUniqueId,
        @RequestParam(value = "elid", required = false) String enterpriseLocationIdentifier,
        @RequestParam(value = "dateStart", required = false) String dateStart,
        @RequestParam(value = "dateEnd", required = false) String dateEnd, HttpServletRequest request,
        HttpServletResponse response) {

    LogEncounterService service = Context.getService(LogEncounterService.class);
    XmlMessageWriter xmlMessagewriter = new XmlMessageWriter();

    String hl7Msg = null;

    Date fromDate = null;
    Date toDate = null;
    Patient p = null;
    ORU_R01 r01 = null;

    log.info("RHEA Controller call detected...");
    log.info("Enterprise Patient Id is :" + patientId);
    log.info("Enterprise Id type is :" + idType);
    log.info("encounterUniqueId is :" + encounterUniqueId);

    GetEncounterLog getEncounterLog = new GetEncounterLog();
    getEncounterLog.setLogTime(new Date());
    getEncounterLog.setPatientId(patientId);
    getEncounterLog.setEncounterUniqueId(encounterUniqueId);

    // first, we create from and to data objects out of the String
    // parameters

    response.setContentType("text/xml");

    if (!idType.equals("ECID")) { // Later on we may need to manage multiple
        // types of ID's. In such a case, this
        // will become more complex
        log.info(RHEAErrorCodes.INVALID_ID_TYPE);
        getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_ID_TYPE,
                RHEAErrorCodes.ID_TYPE_DETAIL, RequestOutcome.BAD_REQUEST.getResultType(), null, null, null);
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        try {
            xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(),
                    RHEAErrorCodes.ID_TYPE_DETAIL);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    try {
        if (dateStart != null)
            fromDate = format.parse(dateStart);
    } catch (ParseException e) {
        log.info(RHEAErrorCodes.INVALID_START_DATE + dateStart);
        getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_START_DATE, null,
                RequestOutcome.BAD_REQUEST.getResultType(), null, null, e);
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        try {
            xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(),
                    e.toString());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    log.info("fromDate is :" + fromDate);
    getEncounterLog.setDateStart(fromDate);

    try {
        if (dateEnd != null)
            toDate = format.parse(dateEnd);
    } catch (ParseException e) {
        log.info(RHEAErrorCodes.INVALID_END_DATE + dateEnd);

        getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_END_DATE, null,
                RequestOutcome.BAD_REQUEST.getResultType(), fromDate, null, e);
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        try {
            xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(),
                    e.toString());

        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    log.info("toDate is :" + toDate);
    getEncounterLog.setDateEnd(toDate);

    // Next, we try to retrieve the matching patient object
    if (patientId != null) {
        PatientIdentifierType patientIdentifierType = Context.getPatientService()
                .getPatientIdentifierTypeByName(idType);
        List<PatientIdentifierType> identifierTypeList = new ArrayList<PatientIdentifierType>();
        identifierTypeList.add(patientIdentifierType);

        List<Patient> patients = Context.getPatientService().getPatients(null, patientId, identifierTypeList,
                false);
        if (patients.size() == 1) {
            p = patients.get(0);
        } else {
            log.info(RHEAErrorCodes.INVALID_RESULTS + patientId);

            getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_RESULTS,
                    RHEAErrorCodes.INVALID_RESULTS_DETAIL, RequestOutcome.BAD_REQUEST.getResultType(), fromDate,
                    toDate, null);
            service.saveGetEncounterLog(getEncounterLog);

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            try {
                xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(),
                        RHEAErrorCodes.INVALID_RESULTS);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return null;
        }
    }

    // if the patient doesn't exist, we need to return 400-BAD REQUEST
    if (p != null) {
        log.info("Patient id : " + p.getPatientId() + "was retreived...");

        if (p != null) {
            // get all the encounters for this patient
            List<Encounter> encounterList = Context.getEncounterService().getEncounters(p, null, fromDate,
                    toDate, null, null, null, false);

            // if the enconteruniqueId is not null, we can isolate the given
            // encounter

            if (encounterUniqueId != null) {
                Iterator<Encounter> i = encounterList.iterator();
                while (i.hasNext()) {
                    if (!i.next().getUuid().equals(encounterUniqueId))
                        i.remove();
                }
            }

            if (enterpriseLocationIdentifier != null) {

                getEncounterLog.setEnterpriseLocationId(enterpriseLocationIdentifier);

                Iterator<Encounter> i = encounterList.iterator();
                while (i.hasNext()) {

                    String elidString = i.next().getLocation().getDescription();
                    String elid = null;

                    if (elidString != null) {
                        final Matcher matcher = Pattern.compile(":").matcher(elidString);
                        if (matcher.find()) {
                            elid = elidString.substring(matcher.end()).trim();
                        }
                        if (elid != null) {
                            if (elid.equals(enterpriseLocationIdentifier)) {
                                i.remove();
                            }
                        }
                    }
                }
            }

            log.info("Calling the ORU_R01 parser...");

            SortedSet<MatchingEncounters> encounterSet = new TreeSet<MatchingEncounters>();

            for (Encounter e : encounterList) {
                MatchingEncounters matchingEncounters = new MatchingEncounters();
                matchingEncounters.setGetEncounterLog(getEncounterLog);
                matchingEncounters.setEncounterId(e.getEncounterId());

                encounterSet.add(matchingEncounters);
            }

            if (encounterList.size() > 0)
                getEncounterLog.setResult(RequestOutcome.RESULTS_RETRIEVED.getResultType());
            if (encounterList.size() == 0) {
                getEncounterLog.setResult(RequestOutcome.NO_RESULTS.getResultType()); // Terrible logging methods !

                getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_RESULTS,
                        RHEAErrorCodes.INVALID_RESULTS_DETAIL, RequestOutcome.NO_RESULTS.getResultType(),
                        fromDate, toDate, null);
                service.saveGetEncounterLog(getEncounterLog);

                response.setStatus(HttpServletResponse.SC_OK); // If no
                // matching
                // encounters
                // were
                // retrived,
                // we
                // display
                // 200. OK.
                // Is this
                // correct ?

                return null;
            }

            // Now we will generate the HL7 message

            GenerateORU_R01 R01Util = new GenerateORU_R01();
            try {
                r01 = R01Util.generateORU_R01Message(p, encounterList);
                hl7Msg = R01Util.getMessage(r01);

            } catch (Exception e) {

                getEncounterLog = util.getLogger(getEncounterLog, RequestOutcome.BAD_REQUEST.getResultType(),
                        null, RequestOutcome.BAD_REQUEST.getResultType(), fromDate, toDate, e);
                service.saveGetEncounterLog(getEncounterLog);

                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                try {
                    xmlMessagewriter.parseMessage(response.getWriter(),
                            RequestOutcome.BAD_REQUEST.getResultType(), e.toString());
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                return null;
            }
            getEncounterLog.getMatchingEncounters().clear();
            getEncounterLog.setMatchingEncounters(encounterSet);
        }

        try {

            service.saveGetEncounterLog(getEncounterLog);
            response.setStatus(HttpServletResponse.SC_OK);

            return hl7Msg;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.application.utils.FastDateParser.java

@Override
public Date parse(final String source, final ParsePosition pos) {
    final int offset = pos.getIndex();
    final Matcher matcher = parsePattern.matcher(source.substring(offset));
    if (!matcher.lookingAt()) {
        return null;
    }//from   w  w  w . j  av  a  2 s. c o  m
    // timing tests indicate getting new instance is 19% faster than cloning
    final Calendar cal = Calendar.getInstance(timeZone, locale);
    cal.clear();

    for (int i = 0; i < strategies.length;) {
        final Strategy strategy = strategies[i++];
        strategy.setCalendar(this, cal, matcher.group(i));
    }
    pos.setIndex(offset + matcher.end());
    return cal.getTime();
}

From source file:com.manydesigns.portofino.pageactions.text.TextAction.java

protected String restoreLocalUrls(String content) {
    Pattern pattern = Pattern.compile(PORTOFINO_HREF_PATTERN);
    Matcher matcher = pattern.matcher(content);
    int lastEnd = 0;
    StringBuilder sb = new StringBuilder();
    while (matcher.find()) {
        String attribute = matcher.group(1);
        String link = matcher.group(2);
        String queryString = matcher.group(4);

        sb.append(content.substring(lastEnd, matcher.start()));
        sb.append(attribute).append("=\"");

        sb.append(context.getRequest().getContextPath());
        //link = convertInternalLinkToPath(link);
        sb.append(link);/* w ww  .j av a 2 s  .c o m*/
        if (!StringUtils.isBlank(queryString)) {
            sb.append(queryString);
        }
        sb.append("\"");

        lastEnd = matcher.end();
    }

    sb.append(content.substring(lastEnd));

    return sb.toString();
}

From source file:com.nttec.everychan.chans.ponyach.PonyachModule.java

@Override
protected WakabaReader getWakabaReader(InputStream stream, UrlPageModel urlModel) {
    return new WakabaReader(stream, DATE_FORMAT, canCloudflare()) {
        private final Pattern aHrefPattern = Pattern.compile("<a\\s+href=\"(.*?)\"", Pattern.DOTALL);
        private final Pattern attachmentSizePattern = Pattern.compile("([\\d\\.]+)[KM]B");
        private final Pattern attachmentPxSizePattern = Pattern.compile("(\\d+)x(\\d+)");
        private final char[] dateFilter = "<span class=\"mobile_date dast-date\">".toCharArray();
        private final char[] attachmentFilter = "<span class=\"filesize fs_".toCharArray();
        private ArrayList<AttachmentModel> myAttachments = new ArrayList<>();
        private int curDatePos = 0;
        private int curAttachmentPos = 0;

        @Override// ww  w.ja va 2s  .  c  om
        protected void customFilters(int ch) throws IOException {
            if (ch == dateFilter[curDatePos]) {
                ++curDatePos;
                if (curDatePos == dateFilter.length) {
                    parseDate(readUntilSequence("</span>".toCharArray()).trim());
                    curDatePos = 0;
                }
            } else {
                if (curDatePos != 0)
                    curDatePos = ch == dateFilter[0] ? 1 : 0;
            }

            if (ch == attachmentFilter[curAttachmentPos]) {
                ++curAttachmentPos;
                if (curAttachmentPos == attachmentFilter.length) {
                    skipUntilSequence(">".toCharArray());
                    myParseAttachment(readUntilSequence("</span>".toCharArray()));
                    curAttachmentPos = 0;
                }
            } else {
                if (curAttachmentPos != 0)
                    curAttachmentPos = ch == attachmentFilter[0] ? 1 : 0;
            }
        }

        @Override
        protected void parseDate(String date) {
            date = date.substring(date.indexOf(' ') + 1);
            super.parseDate(date);
        }

        private void myParseAttachment(String html) {
            Matcher aHrefMatcher = aHrefPattern.matcher(html);
            if (aHrefMatcher.find()) {
                AttachmentModel attachment = new AttachmentModel();
                attachment.path = aHrefMatcher.group(1);
                attachment.thumbnail = attachment.path.replaceAll("/src/(\\d+)/(?:.*?)\\.(.*?)$",
                        "/thumb/$1s.$2");
                if (attachment.thumbnail.equals(attachment.path)) {
                    attachment.thumbnail = null;
                } else {
                    attachment.thumbnail = attachment.thumbnail.replace(".webm", ".png");
                }

                String ext = attachment.path.substring(attachment.path.lastIndexOf('.') + 1);
                switch (ext) {
                case "jpg":
                case "jpeg":
                case "png":
                    attachment.type = AttachmentModel.TYPE_IMAGE_STATIC;
                    break;
                case "gif":
                    attachment.type = AttachmentModel.TYPE_IMAGE_GIF;
                    break;
                case "svg":
                case "svgz":
                    attachment.type = AttachmentModel.TYPE_IMAGE_SVG;
                    break;
                case "webm":
                case "mp4":
                    attachment.type = AttachmentModel.TYPE_VIDEO;
                    break;
                default:
                    attachment.type = AttachmentModel.TYPE_OTHER_FILE;
                }

                Matcher sizeMatcher = attachmentSizePattern.matcher(html);
                if (sizeMatcher.find()) {
                    try {
                        int mul = sizeMatcher.group(0).endsWith("MB") ? 1024 : 1;
                        attachment.size = Math.round(Float.parseFloat(sizeMatcher.group(1)) * mul);
                    } catch (Exception e) {
                        attachment.size = -1;
                    }
                    try {
                        Matcher pxSizeMatcher = attachmentPxSizePattern.matcher(html);
                        if (!pxSizeMatcher.find(sizeMatcher.end()))
                            throw new Exception();
                        attachment.width = Integer.parseInt(pxSizeMatcher.group(1));
                        attachment.height = Integer.parseInt(pxSizeMatcher.group(2));
                    } catch (Exception e) {
                        attachment.width = -1;
                        attachment.height = -1;
                    }
                } else {
                    attachment.size = -1;
                    attachment.width = -1;
                    attachment.height = -1;
                }

                myAttachments.add(attachment);
            }
        }

        @Override
        protected void postprocessPost(PostModel post) {
            post.attachments = myAttachments.toArray(new AttachmentModel[myAttachments.size()]);
            myAttachments.clear();
        }
    };
}

From source file:com.juick.android.JuickMessagesAdapter.java

public static ParsedMessage formatMessageText(final Context ctx, final JuickMessage jmsg, boolean condensed) {
    if (jmsg.parsedText != null) {
        return (ParsedMessage) jmsg.parsedText; // was parsed before
    }/*from  www.ja  v  a2 s .com*/
    getColorTheme(ctx);
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    int spanOffset = 0;
    final boolean isMainMessage = jmsg.getRID() == 0;
    final boolean doCompactComment = !isMainMessage && compactComments;
    if (jmsg.continuationInformation != null) {
        ssb.append(jmsg.continuationInformation + "\n");
        ssb.setSpan(new StyleSpan(Typeface.ITALIC), spanOffset, ssb.length() - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    //
    // NAME
    //
    spanOffset = ssb.length();
    String name = '@' + jmsg.User.UName;
    int userNameStart = ssb.length();
    ssb.append(name);
    int userNameEnd = ssb.length();
    StyleSpan userNameBoldSpan;
    ForegroundColorSpan userNameColorSpan;
    ssb.setSpan(userNameBoldSpan = new StyleSpan(Typeface.BOLD), spanOffset, ssb.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.setSpan(
            userNameColorSpan = new ForegroundColorSpan(
                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME, 0xFFC8934E)),
            spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    ssb.append(' ');
    spanOffset = ssb.length();

    if (!condensed) {
        //
        // TAGS
        //
        String tags = jmsg.getTags();
        if (feedlyFonts)
            tags = tags.toUpperCase();
        ssb.append(tags + "\n");
        if (tags.length() > 0) {
            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TAGS, 0xFF0000CC)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (feedlyFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.dinWebPro), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (helvNueFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        spanOffset = ssb.length();
    }
    if (jmsg.translated) {
        //
        // 'translated'
        //
        ssb.append("translated: ");
        ssb.setSpan(
                new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    int bodyOffset = ssb.length();
    int messageNumberStart = -1, messageNumberEnd = -1;
    if (showNumbers(ctx) && !condensed) {
        //
        // numbers
        //
        if (isMainMessage) {
            messageNumberStart = ssb.length();
            ssb.append(jmsg.getDisplayMessageNo());
            messageNumberEnd = ssb.length();
        } else {
            ssb.append("/" + jmsg.getRID());
            if (jmsg.getReplyTo() != 0) {
                ssb.append("->" + jmsg.getReplyTo());
            }
        }
        ssb.append(" ");
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.MESSAGE_ID, 0xFFa0a5bd)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    //
    // MESSAGE BODY
    //
    String txt = Censor.getCensoredText(jmsg.Text);
    if (!condensed) {
        if (jmsg.Photo != null) {
            txt = jmsg.Photo + "\n" + txt;
        }
        if (jmsg.Video != null) {
            txt = jmsg.Video + "\n" + txt;
        }
    }
    ssb.append(txt);
    boolean ssbChanged = false; // allocation optimization
    // Highlight links http://example.com/
    ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(txt, jmsg.getMID());
    ArrayList<String> urls = new ArrayList<String>();
    for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) {
        setSSBSpan(ssb, new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + foundURL.start, spanOffset + foundURL.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        urls.add(foundURL.url);
        if (foundURL.title != null) {
            ssb.replace(spanOffset + foundURL.title.start - 1, spanOffset + foundURL.title.start, " ");
            ssb.replace(spanOffset + foundURL.title.end, spanOffset + foundURL.title.end + 1, " ");
            ssb.replace(spanOffset + foundURL.start - 1, spanOffset + foundURL.start, "(");
            ssb.replace(spanOffset + foundURL.end, spanOffset + foundURL.end + 1, ")");
            ssb.setSpan(new StyleSpan(Typeface.BOLD), spanOffset + foundURL.title.start,
                    spanOffset + foundURL.title.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        ssbChanged = true;
    }
    // bold italic underline
    if (jmsg.Text.indexOf("*") != -1) {
        setStyleSpans(ssb, spanOffset, Typeface.BOLD, "*");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("/") != 0) {
        setStyleSpans(ssb, spanOffset, Typeface.ITALIC, "/");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("_") != 0) {
        setStyleSpans(ssb, spanOffset, UnderlineSpan.class, "_");
        ssbChanged = true;
    }
    if (ssbChanged) {
        txt = ssb.subSequence(spanOffset, ssb.length()).toString(); // ssb was modified in between
    }

    // Highlight nick
    String accountName = XMPPService.getMyAccountName(jmsg.getMID(), ctx);
    if (accountName != null) {
        int scan = spanOffset;
        String nickScanArea = (ssb + " ").toUpperCase();
        while (true) {
            int myNick = nickScanArea.indexOf("@" + accountName.toUpperCase(), scan);
            if (myNick != -1) {
                if (!isNickPart(nickScanArea.charAt(myNick + accountName.length() + 1))) {
                    setSSBSpan(ssb,
                            new BackgroundColorSpan(
                                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME_ME, 0xFF938e00)),
                            myNick - 1, myNick + accountName.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                scan = myNick + 1;
            } else {
                break;
            }
        }
    }

    // Highlight messages #1234
    int pos = 0;
    Matcher m = getCrossReferenceMsgPattern(jmsg.getMID()).matcher(txt);
    while (m.find(pos)) {
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + m.start(), spanOffset + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        pos = m.end();
    }

    SpannableStringBuilder compactDt = null;
    if (!condensed) {

        // found messages count (search results)
        if (jmsg.myFoundCount != 0 || jmsg.hisFoundCount != 0) {
            ssb.append("\n");
            int where = ssb.length();
            if (jmsg.myFoundCount != 0) {
                ssb.append(ctx.getString(R.string.MyReplies_) + jmsg.myFoundCount + "  ");
            }
            if (jmsg.hisFoundCount != 0) {
                ssb.append(ctx.getString(R.string.UserReplies_) + jmsg.hisFoundCount);
            }
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                    where, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        int rightPartOffset = spanOffset = ssb.length();

        if (!doCompactComment) {
            //
            // TIME (bottom of message)
            //

            try {
                DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                if (date.endsWith("/76"))
                    date = date.substring(0, date.length() - 3); // special case for no year in datasource
                ssb.append("\n" + date + " ");
            } catch (Exception e) {
                ssb.append("\n[fmt err] ");
            }

            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            compactDt = new SpannableStringBuilder();
            try {
                if (true || jmsg.deltaTime != Long.MIN_VALUE) {
                    compactDt.append(com.juickadvanced.Utils.toRelaviteDate(jmsg.Timestamp.getTime(), russian));
                } else {
                    DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                    String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                    if (date.endsWith("/76"))
                        date = date.substring(0, date.length() - 3); // special case for no year in datasource
                    compactDt.append(date);
                }
            } catch (Exception e) {
                compactDt.append("\n[fmt err] ");
            }
            compactDt.setSpan(
                    new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), 0,
                    compactDt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        spanOffset = ssb.length();

        //
        // Number of REPLIES
        //
        if (jmsg.replies > 0) {
            String replies = Replies + jmsg.replies;
            ssb.append(" " + replies);
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.NUMBER_OF_COMMENTS, 0xFFC8934E)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new WrapTogetherSpan() {
            }, spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!doCompactComment) {
            // right align
            ssb.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), rightPartOffset, ssb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), bodyOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    LeadingMarginSpan.LeadingMarginSpan2 userpicSpan = null;
    if (showUserpics(ctx) && !condensed) {
        userpicSpan = new LeadingMarginSpan.LeadingMarginSpan2() {
            @Override
            public int getLeadingMarginLineCount() {
                if (_wrapUserpics) {
                    return 2;
                } else {
                    return 22222;
                }
            }

            @Override
            public int getLeadingMargin(boolean first) {
                if (first) {
                    return (int) (2 * getLineHeight(ctx, (double) textScale));
                } else {
                    return 0;
                }
            }

            @Override
            public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                    CharSequence text, int start, int end, boolean first, Layout layout) {
            }
        };
        ssb.setSpan(userpicSpan, 0, ssb.length(), 0);
    }
    ParsedMessage parsedMessage = new ParsedMessage(ssb, urls);
    parsedMessage.userpicSpan = userpicSpan;
    parsedMessage.userNameBoldSpan = userNameBoldSpan;
    parsedMessage.userNameColorSpan = userNameColorSpan;
    parsedMessage.userNameStart = userNameStart;
    parsedMessage.userNameEnd = userNameEnd;
    parsedMessage.messageNumberStart = messageNumberStart;
    parsedMessage.messageNumberEnd = messageNumberEnd;
    parsedMessage.compactDate = compactDt;
    return parsedMessage;
}

From source file:ca.uhn.hl7v2.testpanel.model.msg.Hl7V2MessageCollection.java

private synchronized void doSetSourceMessageXml(String theMessage) {
    int rangeStart = 0;
    int rangeEnd = 0;

    Pattern p = Pattern.compile("<([A-Za-z0-9_]+).*?>");
    Matcher m = p.matcher(theMessage);

    while (rangeStart < theMessage.length() && m.find(rangeStart)) {

        int startIndex = m.start();
        String tagName = m.group(1);

        Pattern endP = Pattern.compile("</" + tagName + "(\\s.*?)?>");
        Matcher endM = endP.matcher(theMessage);
        boolean foundEnd = endM.find(startIndex);

        if (foundEnd) {

            String fullMsg = theMessage.substring(startIndex, endM.end());
            Hl7V2MessageXml nextMsg = new Hl7V2MessageXml();
            nextMsg.setIndexWithinCollection(myMessages.size());
            nextMsg.setRuntimeProfile(myRuntimeProfile);
            nextMsg.setEncoding(Hl7V2EncodingTypeEnum.XML);
            try {
                nextMsg.setSourceMessage(fullMsg);
                myMessages.add(nextMsg);
            } catch (PropertyVetoException e) {
                UnknownMessage nextUnk = new UnknownMessage(fullMsg);
                myMessages.add(nextUnk);
            }//from   w ww. java 2s  .  co  m

            rangeEnd = endM.end();

        } else {

            String fullMsg = theMessage.substring(startIndex);
            UnknownMessage nextUnk = new UnknownMessage(fullMsg);
            myMessages.add(nextUnk);
            rangeEnd = theMessage.length();

        }

        myMessageRanges.add(new Range(rangeStart, rangeEnd));
        rangeStart = rangeEnd;

    }

    // for (String nextString : msgs) {
    //
    // if (StringUtils.isNotBlank(nextString)) {
    //
    // nextString = "<?xml" + nextString;
    // Hl7V2MessageXml nextMsg = new Hl7V2MessageXml();
    // nextMsg.setIndexWithinCollection(myMessages.size());
    // nextMsg.setRuntimeProfile(myRuntimeProfile);
    // nextMsg.setEncoding(Hl7V2EncodingTypeEnum.XML);
    // try {
    // nextMsg.setSourceMessage(nextString);
    // myMessages.add(nextMsg);
    // } catch (PropertyVetoException e) {
    // UnknownMessage nextUnk = new UnknownMessage(nextString);
    // myMessages.add(nextUnk);
    // }
    //
    // }
    // }
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

/**
 * Internal implementation to add a list of documents to a presentation; either as a single slide or a series of slides.
 * @param imageSource the image source to convert images to data.
 * @param ppt the presentation to add to.
 * @param sl the slide to add to (can be null if pagination is enabled).
 * @param anchor bounding rectangle to draw onto, in PowerPoint coordinates.
 * @param paginate whether to render results as multiple slides if they don't fit on one slide.
 * @param data the documents to render.//  w ww .j  a  va 2 s  .  co  m
 * @param results optional string to render into the top-left corner of the available space.
 *                  Will appear on each page if pagination is enabled.
 * @param sortBy optional string to render into the top-right corner of the available space.
 *                  Will appear on each page if pagination is enabled.
 */
private static void addList(final ImageSource imageSource, final XMLSlideShow ppt, XSLFSlide sl,
        final Rectangle2D.Double anchor, final boolean paginate, final ListData data, final String results,
        final String sortBy) {
    final double
    // How much space to leave at the left and right edge of the slide
    xMargin = 20,
            // How much space to leave at the top
            yMargin = 5,
            // Size of the icon
            iconWidth = 20, iconHeight = 24,
            // Find's thumbnail height is 97px by 55px, hardcoded in the CSS in .document-thumbnail
            thumbScale = 0.8, thumbW = 97 * thumbScale, thumbH = 55 * thumbScale,
            // Margin around the thumbnail
            thumbMargin = 4.,
            // Space between list items
            listItemMargin = 5.;

    final Pattern highlightPattern = Pattern
            .compile("<HavenSearch-QueryText-Placeholder>(.*?)</HavenSearch-QueryText-Placeholder>");

    double yCursor = yMargin + anchor.getMinY(), xCursor = xMargin + anchor.getMinX();

    int docsOnPage = 0;

    final Document[] docs = data.getDocs();
    for (int docIdx = 0; docIdx < docs.length; ++docIdx) {
        final Document doc = docs[docIdx];

        if (sl == null) {
            sl = ppt.createSlide();
            yCursor = yMargin + anchor.getMinY();
            xCursor = xMargin + anchor.getMinX();
            docsOnPage = 0;

            double yStep = 0;

            if (StringUtils.isNotBlank(results)) {
                final XSLFTextBox textBox = sl.createTextBox();
                textBox.clearText();
                final Rectangle2D.Double textBounds = new Rectangle2D.Double(xCursor, yCursor,
                        Math.max(0, anchor.getMaxX() - xCursor - xMargin), 20);
                textBox.setAnchor(textBounds);

                addTextRun(textBox.addNewTextParagraph(), results, 12., Color.LIGHT_GRAY);

                yStep = textBox.getTextHeight();
            }

            if (StringUtils.isNotBlank(sortBy)) {
                final XSLFTextBox sortByEl = sl.createTextBox();
                sortByEl.clearText();
                final XSLFTextParagraph sortByText = sortByEl.addNewTextParagraph();
                sortByText.setTextAlign(TextParagraph.TextAlign.RIGHT);

                addTextRun(sortByText, sortBy, 12., Color.LIGHT_GRAY);

                sortByEl.setAnchor(new Rectangle2D.Double(xCursor, yCursor,
                        Math.max(0, anchor.getMaxX() - xCursor - xMargin), 20));

                yStep = Math.max(sortByEl.getTextHeight(), yStep);
            }

            if (yStep > 0) {
                yCursor += listItemMargin + yStep;
            }
        }

        XSLFAutoShape icon = null;
        if (data.isDrawIcons()) {
            icon = sl.createAutoShape();
            icon.setShapeType(ShapeType.SNIP_1_RECT);
            icon.setAnchor(new Rectangle2D.Double(xCursor, yCursor + listItemMargin, iconWidth, iconHeight));
            icon.setLineColor(Color.decode("#888888"));
            icon.setLineWidth(2.0);

            xCursor += iconWidth;
        }

        final XSLFTextBox listEl = sl.createTextBox();
        listEl.clearText();
        listEl.setAnchor(new Rectangle2D.Double(xCursor, yCursor,
                Math.max(0, anchor.getMaxX() - xCursor - xMargin), Math.max(0, anchor.getMaxY() - yCursor)));

        final XSLFTextParagraph titlePara = listEl.addNewTextParagraph();
        addTextRun(titlePara, doc.getTitle(), data.getTitleFontSize(), Color.BLACK).setBold(true);

        if (StringUtils.isNotBlank(doc.getDate())) {
            final XSLFTextParagraph datePara = listEl.addNewTextParagraph();
            datePara.setLeftMargin(5.);
            addTextRun(datePara, doc.getDate(), data.getDateFontSize(), Color.GRAY).setItalic(true);
        }

        if (StringUtils.isNotBlank(doc.getRef())) {
            addTextRun(listEl.addNewTextParagraph(), doc.getRef(), data.getRefFontSize(), Color.GRAY);
        }

        final double thumbnailOffset = listEl.getTextHeight();

        final XSLFTextParagraph contentPara = listEl.addNewTextParagraph();

        Rectangle2D.Double pictureAnchor = null;
        XSLFPictureData pictureData = null;

        if (StringUtils.isNotBlank(doc.getThumbnail())) {
            try {
                // Picture reuse is automatic
                pictureData = addPictureData(imageSource, ppt, doc.getThumbnail());
                // We reserve space for the picture, but we don't actually add it yet.
                // The reason is we may have to remove it later if it doesn't fit; but due to a quirk of OpenOffice,
                //   deleting the picture shape removes the pictureData as well; which is a problem since the
                //   pictureData can be shared between multiple pictures.
                pictureAnchor = new Rectangle2D.Double(xCursor, yCursor + thumbnailOffset + thumbMargin, thumbW,
                        thumbH);

                // If there is enough horizontal space, put the text summary to the right of the thumbnail image,
                //    otherwise put it under the thumbnail,
                if (listEl.getAnchor().getWidth() > 2.5 * thumbW) {
                    contentPara.setLeftMargin(thumbW);
                } else {
                    contentPara.addLineBreak().setFontSize(thumbH);
                }

            } catch (RuntimeException e) {
                // if there's any errors, we'll just ignore the image
            }
        }

        final String rawSummary = doc.getSummary();
        if (StringUtils.isNotBlank(rawSummary)) {
            // HTML treats newlines and multiple whitespace as a single whitespace.
            final String summary = rawSummary.replaceAll("\\s+", " ");
            final Matcher matcher = highlightPattern.matcher(summary);
            int idx = 0;

            while (matcher.find()) {
                final int start = matcher.start();

                if (idx < start) {
                    addTextRun(contentPara, summary.substring(idx, start), data.getSummaryFontSize(),
                            Color.DARK_GRAY);
                }

                addTextRun(contentPara, matcher.group(1), data.getSummaryFontSize(), Color.DARK_GRAY)
                        .setBold(true);
                idx = matcher.end();
            }

            if (idx < summary.length()) {
                addTextRun(contentPara, summary.substring(idx), data.getSummaryFontSize(), Color.DARK_GRAY);
            }
        }

        double elHeight = Math.max(listEl.getTextHeight(), iconHeight);
        if (pictureAnchor != null) {
            elHeight = Math.max(elHeight, pictureAnchor.getMaxY() - yCursor);
        }

        yCursor += elHeight;
        xCursor = xMargin + anchor.getMinX();

        docsOnPage++;

        if (yCursor > anchor.getMaxY()) {
            if (docsOnPage > 1) {
                // If we drew more than one list element on this page; and we exceeded the available space,
                //   delete the last element's shapes and redraw it on the next page.
                // We don't have to remove the picture since we never added it.
                sl.removeShape(listEl);
                if (icon != null) {
                    sl.removeShape(icon);
                }

                --docIdx;
            } else if (pictureAnchor != null) {
                // We've confirmed we need the picture, add it.
                sl.createPicture(pictureData).setAnchor(pictureAnchor);
            }

            sl = null;

            if (!paginate) {
                break;
            }
        } else {
            yCursor += listItemMargin;

            if (pictureAnchor != null) {
                // We've confirmed we need the picture, add it.
                sl.createPicture(pictureData).setAnchor(pictureAnchor);
            }
        }
    }
}