Example usage for java.util.regex MatchResult group

List of usage examples for java.util.regex MatchResult group

Introduction

In this page you can find the example usage for java.util.regex MatchResult group.

Prototype

public String group(int group);

Source Link

Document

Returns the input subsequence captured by the given group during the previous match operation.

Usage

From source file:com.edgenius.wiki.render.filter.LinkFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    int idx = result.groupCount();

    if (idx < 1) {
        // failure tolerance
        buffer.append(result.group(0));
        return;/*from  w w  w.j  a va  2 s . c om*/
    }

    Region bodyRegion = context.getCurrentRegion();
    LinkModel model = getLinkModel(result, bodyRegion);

    LinkRenderHelper linkRenderHelper = context.getLinkRenderHelper();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //   Concatenate LINK URL
    String view = model.getView(), link = model.getLink(), anchor = model.getAnchor(),
            extSpaceUname = model.getSpaceUname();
    int type = model.getType();
    ObjectPosition pos = null;
    if (LinkUtil.isExtLink(link)) {
        // if it start from "http://" etc. start, it is extlink

        //use ObjectPosition rather than direct render to String, is for link surrounding content
        //for example, [!image.jpg!>http://www.edgenius.com], the !image.jpg! can render as well
        pos = new ObjectPosition(result.group(0));
        pos.serverHandler = LinkHandler.HANDLER;
        pos.uuid = context.createUniqueKey(false);
        pos.values = new HashMap<String, String>();
        //if it is [view>http://foo.com] format, view will be reset in subRegion()
        pos.values.put(NameConstants.VIEW, view);
        //Please note, NameConstants.NAME won't be set!!! See LinkFilter, it treats if(name==null) as extlink format.
        context.getObjectList().add(pos);

        //here will make LinkHandler process content part beside <a>, ie, <a>content</a>
        model.setView(pos.uuid);

        //model view is pos.uuid now, will replace in subRegion render.
        buffer.append(linkRenderHelper.getExternalImage(context, link));
        buffer.append(model.toRichAjaxTag());

    } else {
        if (extSpaceUname != null) {
            if (!linkRenderHelper.exists(extSpaceUname, link)) {
                //does not allow create new page from outside space. here only show link break image.
                buffer.append(linkRenderHelper.getExtspaceLinkBreakImage(context));
            }
            if (anchor != null) {
                pos = linkRenderHelper.appendExtSpaceLink(buffer, extSpaceUname, link, view, anchor);
            } else {
                pos = linkRenderHelper.appendExtSpaceLink(buffer, extSpaceUname, link, view);
            }
        } else {
            //if link is blank, maybe anchor only format(redir in same page) [view>#anchor] 
            if (type == LinkModel.LINK_TO_ATTACHMENT) {
                //file attachment link
                pos = new ObjectPosition(result.group(0));
                pos.serverHandler = LinkHandler.HANDLER;
                pos.uuid = context.createUniqueKey(false);
                pos.values.put(NameConstants.VIEW, view);
                //remove leading "^"
                pos.values.put(NameConstants.NAME, link.substring(1));
                pos.values.put(NameConstants.TYPE, String.valueOf(LinkModel.LINK_TO_ATTACHMENT));
                context.getObjectList().add(pos);
                buffer.append(pos.uuid);

            } else if (StringUtils.isBlank(link) || linkRenderHelper.exists(link)
            //if web service or RSS request, then return page always return valid even the page doesn't exist.
            //For example, shell request the page, it doesn't want to the non-exist page link block back javascript
            //it may want to display 404 error.
                    || RenderContext.RENDER_TARGET_PLAIN_VIEW.equals(context.getRenderTarget())) {
                // Do not add hash if an alias was given
                if (anchor != null) {
                    pos = linkRenderHelper.appendLink(buffer, link, view, anchor);
                } else {
                    pos = linkRenderHelper.appendLink(buffer, link, view);
                }
            } else if (linkRenderHelper.showCreate()) {
                buffer.append(linkRenderHelper.getNonexistImage(context));
                pos = linkRenderHelper.appendCreateLink(buffer, link, view);
                // links with "create" are not cacheable because
                // a missing wiki could be created
                // context.getRenderContext().setCacheable(false);
            } else {
                // cannot display/create wiki, so just display the text
                pos = new ObjectPosition(result.group(0));
                pos.serverHandler = LinkHandler.HANDLER;
                pos.uuid = context.createUniqueKey(false);
                pos.values.put(NameConstants.VIEW, view);
                pos.values.put(NameConstants.NAME, link);
                //this flag will tell LinkHandler "PageNotFound, But no permission to create page" - comparing with external link, ie, http:// etc.
                pos.values.put(NameConstants.TYPE, String.valueOf(LinkModel.LINK_TO_READONLY));
                context.getObjectList().add(pos);
                buffer.append(pos.uuid);
            }
        }
    }

    if (bodyRegion != null && bodyRegion.getSubRegion() != null && pos != null) {
        bodyRegion.getSubRegion().setKey(pos.uuid);
    }
}

From source file:org.teleportr.plugin.BahnDePlugIn.java

public ArrayList<Ride> find(Place orig, Place dest, Date time, Teleporter tlp) {

    StringBuilder url = new StringBuilder();
    url.append("http://mobile.bahn.de/bin/mobil/query.exe/dox?");
    url.append("n=1");

    //        if (orig.city!=null)
    //           Log.d(TAG, "city: "+orig.city);
    if (orig.address != null)
        url.append("&f=2&s=")
                .append(URLEncoder.encode(orig.address + (orig.city != null ? (", " + orig.city) : "") + "!"));
    else/*from   ww w .  j av a  2  s  . co m*/
        url.append("&f=1&s=")
                .append(URLEncoder.encode(orig.name + (orig.city != null ? (", " + orig.city) : "") + "!"));

    if (dest.address != null)
        url.append("&o=2&z=")
                .append(URLEncoder.encode(dest.address + (dest.city != null ? (", " + dest.city) : "") + "!"));
    else
        url.append("&o=1&z=")
                .append(URLEncoder.encode(dest.name + (dest.city != null ? (", " + dest.city) : "") + "!"));

    url.append("&d="); // date
    url.append((new SimpleDateFormat("ddMMyy")).format(time));
    url.append("&t="); // time
    url.append((new SimpleDateFormat("HHmm")).format(time));
    url.append("&start=Suchen");
    //        Log.d(TAG, "url: "+url.toString());

    // fetch
    try {
        Ride r;
        MatchResult m;
        rides.clear();
        Scanner scanner = new Scanner(client.execute(new HttpGet(url.toString())).getEntity().getContent(),
                "iso-8859-1");
        Log.d(TAG, " url: " + url.toString());
        while (scanner.findWithinHorizon("<a href=\"([^\"]*)\">(\\d\\d):(\\d\\d)<br />(\\d\\d):(\\d\\d)",
                10000) != null) {
            m = scanner.match();
            Date dep = parseDate(m.group(2), m.group(3));
            if (dep.getTime() - time.getTime() > 100000) {
                r = new Ride();
                r.orig = orig;
                r.dest = dest;
                r.mode = Ride.MODE_TRANSIT;
                r.dep = dep;
                r.arr = parseDate(m.group(4), m.group(5));
                r.price = -1;
                r.fun = 3;
                r.eco = 3;
                r.fast = 1;
                r.social = 2;
                r.green = 4;
                r.uri = m.group(1).replace("&amp;", "&");

                rides.add(r);
                Log.d(TAG, " + found " + r.uri);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Mist!");
        e.printStackTrace();
    }
    return rides;
}

From source file:de.sub.goobi.helper.VariableReplacer.java

/**
 * Variablen innerhalb eines Strings ersetzen. Dabei vergleichbar zu Ant die
 * Variablen durchlaufen und aus dem Digital Document holen
 *///from  w w w  .j a  va  2s . c o m
public String replace(String inString) {
    if (inString == null) {
        return "";
    }

    /*
     * replace metadata, usage: $(meta.firstchild.METADATANAME)
     */
    for (MatchResult r : findRegexMatches(this.namespaceMeta, inString)) {
        if (r.group(1).toLowerCase().startsWith("firstchild.")) {
            inString = inString.replace(r.group(),
                    getMetadataFromDigitalDocument(MetadataLevel.FIRSTCHILD, r.group(1).substring(11)));
        } else if (r.group(1).toLowerCase().startsWith("topstruct.")) {
            inString = inString.replace(r.group(),
                    getMetadataFromDigitalDocument(MetadataLevel.TOPSTRUCT, r.group(1).substring(10)));
        } else {
            inString = inString.replace(r.group(),
                    getMetadataFromDigitalDocument(MetadataLevel.ALL, r.group(1)));
        }
    }

    // replace paths and files
    try {
        String processpath = fileService
                .getFileName(serviceManager.getProcessService().getProcessDataDirectory(this.process))
                .replace("\\", "/");
        String tifpath = fileService
                .getFileName(serviceManager.getProcessService().getImagesTifDirectory(false, this.process))
                .replace("\\", "/");
        String imagepath = fileService.getFileName(fileService.getImagesDirectory(this.process)).replace("\\",
                "/");
        String origpath = fileService
                .getFileName(serviceManager.getProcessService().getImagesOrigDirectory(false, this.process))
                .replace("\\", "/");
        String metaFile = fileService.getFileName(fileService.getMetadataFilePath(this.process)).replace("\\",
                "/");
        String ocrBasisPath = fileService.getFileName(fileService.getOcrDirectory(this.process)).replace("\\",
                "/");
        String ocrPlaintextPath = fileService.getFileName(fileService.getTxtDirectory(this.process))
                .replace("\\", "/");
        // TODO name ndern?
        String sourcePath = fileService.getFileName(fileService.getSourceDirectory(this.process)).replace("\\",
                "/");
        String importPath = fileService.getFileName(fileService.getImportDirectory(this.process)).replace("\\",
                "/");
        String myprefs = ConfigCore.getParameter("RegelsaetzeVerzeichnis")
                + this.process.getRuleset().getFile();

        /*
         * da die Tiffwriter-Scripte einen Pfad ohne endenen Slash haben
         * wollen, wird diese rausgenommen
         */
        if (tifpath.endsWith(File.separator)) {
            tifpath = tifpath.substring(0, tifpath.length() - File.separator.length()).replace("\\", "/");
        }
        if (imagepath.endsWith(File.separator)) {
            imagepath = imagepath.substring(0, imagepath.length() - File.separator.length()).replace("\\", "/");
        }
        if (origpath.endsWith(File.separator)) {
            origpath = origpath.substring(0, origpath.length() - File.separator.length()).replace("\\", "/");
        }
        if (processpath.endsWith(File.separator)) {
            processpath = processpath.substring(0, processpath.length() - File.separator.length()).replace("\\",
                    "/");
        }
        if (importPath.endsWith(File.separator)) {
            importPath = importPath.substring(0, importPath.length() - File.separator.length()).replace("\\",
                    "/");
        }
        if (sourcePath.endsWith(File.separator)) {
            sourcePath = sourcePath.substring(0, sourcePath.length() - File.separator.length()).replace("\\",
                    "/");
        }
        if (ocrBasisPath.endsWith(File.separator)) {
            ocrBasisPath = ocrBasisPath.substring(0, ocrBasisPath.length() - File.separator.length())
                    .replace("\\", "/");
        }
        if (ocrPlaintextPath.endsWith(File.separator)) {
            ocrPlaintextPath = ocrPlaintextPath
                    .substring(0, ocrPlaintextPath.length() - File.separator.length()).replace("\\", "/");
        }
        if (inString.contains("(tifurl)")) {
            if (SystemUtils.IS_OS_WINDOWS) {
                inString = inString.replace("(tifurl)", "file:/" + tifpath);
            } else {
                inString = inString.replace("(tifurl)", "file://" + tifpath);
            }
        }
        if (inString.contains("(origurl)")) {
            if (SystemUtils.IS_OS_WINDOWS) {
                inString = inString.replace("(origurl)", "file:/" + origpath);
            } else {
                inString = inString.replace("(origurl)", "file://" + origpath);
            }
        }
        if (inString.contains("(imageurl)")) {
            if (SystemUtils.IS_OS_WINDOWS) {
                inString = inString.replace("(imageurl)", "file:/" + imagepath);
            } else {
                inString = inString.replace("(imageurl)", "file://" + imagepath);
            }
        }

        if (inString.contains("(tifpath)")) {
            inString = inString.replace("(tifpath)", tifpath);
        }
        if (inString.contains("(origpath)")) {
            inString = inString.replace("(origpath)", origpath);
        }
        if (inString.contains("(imagepath)")) {
            inString = inString.replace("(imagepath)", imagepath);
        }
        if (inString.contains("(processpath)")) {
            inString = inString.replace("(processpath)", processpath);
        }
        if (inString.contains("(importpath)")) {
            inString = inString.replace("(importpath)", importPath);
        }
        if (inString.contains("(sourcepath)")) {
            inString = inString.replace("(sourcepath)", sourcePath);
        }

        if (inString.contains("(ocrbasispath)")) {
            inString = inString.replace("(ocrbasispath)", ocrBasisPath);
        }
        if (inString.contains("(ocrplaintextpath)")) {
            inString = inString.replace("(ocrplaintextpath)", ocrPlaintextPath);
        }
        if (inString.contains("(processtitle)")) {
            inString = inString.replace("(processtitle)", this.process.getTitle());
        }
        if (inString.contains("(processid)")) {
            inString = inString.replace("(processid)", String.valueOf(this.process.getId().intValue()));
        }
        if (inString.contains("(metaFile)")) {
            inString = inString.replace("(metaFile)", metaFile);
        }
        if (inString.contains("(prefs)")) {
            inString = inString.replace("(prefs)", myprefs);
        }

        if (this.task != null) {
            String stepId = String.valueOf(this.task.getId());
            String stepname = this.task.getTitle();

            inString = inString.replace("(stepid)", stepId);
            inString = inString.replace("(stepname)", stepname);
        }

        // replace WerkstueckEigenschaft, usage: (product.PROPERTYTITLE)

        for (MatchResult r : findRegexMatches("\\(product\\.([\\w.-]*)\\)", inString)) {
            String propertyTitle = r.group(1);
            for (Workpiece ws : this.process.getWorkpieces()) {
                for (Property workpieceProperty : ws.getProperties()) {
                    if (workpieceProperty.getTitle().equalsIgnoreCase(propertyTitle)) {
                        inString = inString.replace(r.group(), workpieceProperty.getValue());
                        break;
                    }
                }
            }
        }

        // replace Vorlageeigenschaft, usage: (template.PROPERTYTITLE)

        for (MatchResult r : findRegexMatches("\\(template\\.([\\w.-]*)\\)", inString)) {
            String propertyTitle = r.group(1);
            for (Template v : this.process.getTemplates()) {
                for (Property templateProperty : v.getProperties()) {
                    if (templateProperty.getTitle().equalsIgnoreCase(propertyTitle)) {
                        inString = inString.replace(r.group(), templateProperty.getValue());
                        break;
                    }
                }
            }
        }

        // replace Prozesseigenschaft, usage: (process.PROPERTYTITLE)

        for (MatchResult r : findRegexMatches("\\(process\\.([\\w.-]*)\\)", inString)) {
            String propertyTitle = r.group(1);
            List<ProcessProperty> ppList = PropertyParser.getPropertiesForProcess(this.process);
            for (ProcessProperty pe : ppList) {
                if (pe.getName().equalsIgnoreCase(propertyTitle)) {
                    inString = inString.replace(r.group(), pe.getValue());
                    break;
                }
            }

        }

    } catch (IOException e) {
        logger.error(e);
    }

    return inString;
}

From source file:de.iteratec.iteraplan.general.PropertiesTest.java

/**
 * @see {@link #testJspKeys()}/*from w  ww .  j  a  va2 s. c om*/
 * @param collectedBundleKeys
 *          Bundle keys collected so far. Acts as in-out parameter.
 * @param p
 *          The pattern to find.
 * @param fileToProcess
 *          The file to be looked at.
 * @return true if a bundle key was missing.
 * @throws FileNotFoundException
 */
private boolean parseJspForBundleKeys(Set<String> collectedBundleKeys, Pattern p, File fileToProcess)
        throws FileNotFoundException {
    boolean wasSuccessful = true;

    if (fileToProcess.isDirectory()) {
        for (File f : fileToProcess.listFiles()) {
            boolean containedSuccess = parseJspForBundleKeys(collectedBundleKeys, p, f);
            if (!containedSuccess) {
                wasSuccessful = false;
            }
        }
    } else if (fileToProcess.getName().toLowerCase().endsWith("jsp")) {
        Scanner sc = new Scanner(fileToProcess);
        StringBuffer jspAsStringBuffer = new StringBuffer();
        while (sc.hasNextLine()) {
            jspAsStringBuffer.append(sc.nextLine());
        }
        String jspAsString = jspAsStringBuffer.toString();
        MatchResult result = null;
        sc = new Scanner(jspAsString);
        while (true) {
            if (sc.findInLine(p) == null) {
                break;
            }
            result = sc.match();
            String bundleKey = result.group(POSITION_OF_PROPERTY_IN_JSP_TAG); // refers to regexp which is passed into this method
            collectedBundleKeys.add(bundleKey);

            // omit registered keys and keys which contain variables
            if (!ACCEPTABLE_MISSES_LIST.contains(bundleKey) && !(bundleKey.contains("$"))) {
                for (LanguageFile l : languageFiles) {
                    if (!l.keySet().contains(bundleKey)) {
                        wasSuccessful = false;
                        LOGGER.info(
                                "Bundle key {0} defined in JSP {1} was not found in {2} ApplicationResources.properties!",
                                bundleKey, fileToProcess, l.language);
                    }
                }
            }
        }
    }

    return wasSuccessful;
}

From source file:com.google.mr4c.util.CustomFormat.java

public Map<String, String> parse(String str) {
    if (!matches(str)) {
        throw new IllegalArgumentException(String.format("[%s] doesn't match pattern [%s]", str, m_pattern));
    }//from  ww  w.ja v a 2 s .com
    Scanner scanner = new Scanner(str);
    scanner.findWithinHorizon(m_regex, 0);
    MatchResult result = scanner.match();
    Map<String, String> vals = new HashMap<String, String>();
    if (result.groupCount() != m_nameList.size()) {
        // this shouldn't be able to happen
        throw new IllegalStateException(
                String.format("[%s] doesn't match pattern [%s]; found %d matches, expected %d", str, m_pattern,
                        result.groupCount(), m_nameList.size()));
    }
    for (int i = 1; i <= result.groupCount(); i++) {
        String name = m_nameList.get(i - 1);
        String val = result.group(i);
        if (vals.containsKey(name)) {
            if (!vals.get(name).equals(val)) {
                throw new IllegalArgumentException(
                        String.format("[%s]doesnt match pattern [%s]; variable [%s] has values [%s] and [%s]",
                                str, m_pattern, name, val, vals.get(name)));
            }
        }
        vals.put(name, result.group(i));
    }
    return vals;
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

/**
* Loads the reference data contained in separate data files
*///ww  w  .j a  va  2  s .co  m
protected void loadExternalReferenceData() {
    try {
        InputStream propertyFileStream = Environment.class.getResourceAsStream(EXTERNAL_DATA_PROPERTY_FILE);
        if (propertyFileStream == null)
            propertyFileStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(EXTERNAL_DATA_PROPERTY_FILE);
        if (propertyFileStream == null) {
            log.warn("'" + EXTERNAL_DATA_PROPERTY_FILE
                    + "' property file not found for loading reference data contained " + "in external files.");
            return;
        }
        Properties props = new java.util.Properties();
        props.load(propertyFileStream);

        final Enumeration keys = props.keys();
        while (keys.hasMoreElements()) {
            final String className = (String) keys.nextElement();
            final String dataFileName = props.getProperty(className);
            InputStream stream = Environment.class.getResourceAsStream(dataFileName);
            if (stream == null)
                stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(dataFileName);
            Scanner sc = new Scanner(stream);
            int rowsAdded = 0;
            if (sc.hasNextLine()) {
                sc.findInLine(
                        "\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"");
                try {
                    MatchResult result = sc.match();
                    final Class refClass = Class.forName(className);
                    final Object refObject = refClass.newInstance();
                    if (refObject instanceof AbstractReferenceEntity) {
                        final AbstractReferenceEntity refEntity = (AbstractReferenceEntity) refObject;
                        refEntity.setCode(result.group(0));
                        refEntity.setLabel(result.group(1));
                        refEntity.setDescription(result.group(2));
                        HibernateUtil.getSession().save(refEntity);
                        rowsAdded++;
                    }
                } catch (Exception e) {
                    log.error(className + ": Error at data row count = " + rowsAdded + " \n"
                            + ExceptionUtils.getStackTrace(e));
                }
            }
            sc.close();
            log.info(className + ", Rows Added = " + rowsAdded);
        }
        //InputStream stream = new FileInputStream("e:\\netspective\\medigy\\persistence\\database\\refdata\\icd9-codes.txt");
    } catch (Exception e) {
        log.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java

/**
 * Get PDF information with pdfinfo:// w ww  .j  ava  2  s.  c  om
 * - "Pages: X": number of pages;
 * - "Page X size: www.ww hhh.hh": size of each page, in pts.
 * @returns a map:
 * - [Pages][n]
 * - [Page 1][111.11 222.22]
 * - [Page i][www.ww hhh.hh]
 * - [Page n][999.99 1000.00]
 */
private static Map<String, String> getPDFProperties(ImageRecord input) throws DjatokaException {
    logger.debug("Getting PDF info");

    try {
        setPDFCommandsPath();
    } catch (IllegalStateException e) {
        logger.error("Failed to set PDF commands path: ", e);
        throw e;
    }

    HashMap<String, String> pdfProperties = new HashMap<String, String>();

    String sourcePath = null;

    if (input.getImageFile() != null) {
        logger.debug("PDFInfo image file: " + input.getImageFile());
        sourcePath = input.getImageFile();
    } else if (input.getObject() != null && (input.getObject() instanceof InputStream)) {
        FileInputStream fis = null;
        fis = (FileInputStream) input.getObject();
        File in;

        // Copy to tmp file
        try {
            String cacheDir = OpenURLJP2KService.getCacheDir();
            if (cacheDir != null) {
                in = File.createTempFile("tmp", ".pdf", new File(cacheDir));
            } else {
                in = File.createTempFile("tmp", ".pdf");
            }
            in.deleteOnExit();

            FileOutputStream fos = new FileOutputStream(in);
            IOUtils.copyStream(fis, fos);
        } catch (IOException e) {
            logger.error(e, e);
            throw new DjatokaException(e);
        }
        sourcePath = in.getAbsolutePath();
    } else {
        throw new DjatokaException("File not defined and Input Object Type " + input //.getObject().getClass().getName()
                + " is not supported");
    }

    String pdfinfoCmd[] = PDFINFO_COMMAND.clone();
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_BIN] = pdfinfoPath;
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_FIRSTPAGE] = "1";
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_LASTPAGE] = "-1"; // Last page even we not knowing its number.
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_FILE] = sourcePath;
    Process pdfProc = null;
    try {
        ArrayList<MatchResult> pageSizes = new ArrayList<MatchResult>();
        MatchResult pages = null;

        pdfProc = Runtime.getRuntime().exec(pdfinfoCmd);
        BufferedReader lr = new BufferedReader(new InputStreamReader(pdfProc.getInputStream()));
        String line;
        for (line = lr.readLine(); line != null; line = lr.readLine()) {
            Matcher mm1 = PAGES_PATT.matcher(line);
            if (mm1.matches())
                pages = mm1.toMatchResult();
            Matcher mm2 = MEDIABOX_PATT.matcher(line);
            if (mm2.matches())
                pageSizes.add(mm2.toMatchResult());
        }

        int istatus = pdfProc.waitFor();
        if (istatus != 0)
            logger.error("pdfinfo proc failed, exit status=" + istatus + ", file=" + sourcePath);

        if (pages == null) {
            logger.error("Did not find 'Pages' line in output of pdfinfo command: "
                    + Arrays.deepToString(pdfinfoCmd));
            pdfProperties.put("Pages", "0");
        } else {
            //int n = Integer.parseInteger(pages.group(1));
            pdfProperties.put("Pages", pages.group(1));
        }

        if (pageSizes.isEmpty()) {
            logger.error("Did not find \"Page X size\" lines in output of pdfinfo command: "
                    + Arrays.deepToString(pdfinfoCmd));
            throw new IllegalArgumentException("Failed to get pages size of PDF with pdfinfo.");
        } else {
            for (MatchResult mr : pageSizes) {
                String page = mr.group(1);

                float x0 = Float.parseFloat(mr.group(2));
                float y0 = Float.parseFloat(mr.group(3));
                float x1 = Float.parseFloat(mr.group(4));
                float y1 = Float.parseFloat(mr.group(5));
                float w = Math.abs(x1 - x0);
                float h = Math.abs(y1 - y0);
                // Have to scale page sizes by max dpi (MAX_DPI / DEFAULT_DENSITY). Otherwise, BookReader.js will request the wrong zoom level (svc.level).
                float ws = w * MAX_DPI / DEFAULT_DENSITY;
                float hs = h * MAX_DPI / DEFAULT_DENSITY;
                String width = "" + ws; //mr.group(2);
                String height = "" + hs; //mr.group(3);
                pdfProperties.put("Page " + page, width + " " + height);
            }
        }

    } catch (Exception e) {
        logger.error("Failed getting PDF information: ", e);
        throw new DjatokaException("Failed getting PDF information: ", e);
    } finally {
        // Our exec() should just consume one of the streams, but we want to stay safe.
        // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream());
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream());
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream());
    }

    return pdfProperties;
}

From source file:com.edgenius.wiki.render.filter.MacroFilter.java

private void handleMacro(boolean paired, StringBuffer buffer, MatchResult result, RenderContext context,
        List<Region> pairRegions, String startTagBody) {
    //don't eat first character, which is checking for Escape "\"
    //result group: 1-macro name, 2-parameter, 3-surrounding content
    String macroName = result.group(1);

    if (macroName != null) {
        // {$peng} are variables not macros.
        if (!macroName.startsWith("$")) {
            try {
                Macro macro = macroMgr.getMacro(macroName);
                if (macro.isPaired() != paired) {
                    String body = result.group(0);
                    int start = buffer.length();
                    int end = start + body.length();
                    Region pair = new Region(start, end);
                    //no parameter, then mark as unknown, otherwise, must be a start macro
                    if (StringUtils.isBlank(result.group(2))) {
                        pair.setKey(MACRO_REGION_KEY_UNKNOWN);
                    } else {
                        pair.setKey(MACRO_REGION_KEY_START);
                    }/*from  www  .  ja v  a2s . c om*/
                    pair.setContent(macroName);
                    pair.setBody(body);
                    //sum into list
                    pairRegions.add(pair);

                    buffer.append(body);
                    return;
                }

                BaseMacroParameter mParams = new BaseMacroParameter();
                mParams.setMacroName(macroName);
                mParams.setRenderContext(context);

                switch (result.groupCount()) {
                case 3:
                    if (macro instanceof ImmutableContentMacro) {
                        if (context.getCurrentRegion() == null) {
                            AuditLogger
                                    .error("Unexpected case: Immutable fitler cannot find out current region."
                                            + result.group());
                        }

                        mParams.setContent(
                                context.getCurrentRegion() != null ? context.getCurrentRegion().getContent()
                                        : result.group(3));
                    } else {
                        mParams.setContent(result.group(3));
                    }
                    //no break!
                case 2:
                    //parameter won't be HTML entity format. And macro parameter value slash unescape will do while 
                    //parameter parsed, inside MacroParameter.setParams().
                    mParams.setParams(StringEscapeUtil.unescapeHtml(result.group(2)));
                }

                // recursively filter macros within macros
                if (macro.isProcessEmbedded() && mParams.getContent() != null) {
                    mParams.setContent(filter(mParams.getContent(), context));
                }

                if (mParams.getContent() == null)
                    mParams.setContent("");

                //if paired markup, the startTagBody is parsed from filter beginning singleMarkupParser...
                //for single markup, then just the whole text.
                mParams.setStartMarkup(paired ? startTagBody : result.group(0));

                macro.execute(buffer, mParams);
            } catch (MalformedMacroException e) {
                buffer.append(
                        RenderUtil.renderError("Invalid macro: " + e.getMessage(), result.group(0)).toString());
            } catch (Throwable e) {
                log.warn("MacroFilter: unable to format macro: " + result.group(0));
                buffer.append(result.group(0));
                return;
            }
        } else {
            // {$peng}, so far, do nothing for this format
            buffer.append(result.group(0));
        }
    } else {
        //unable to parse out correct macro name, render original String
        buffer.append(result.group(0));
    }
}

From source file:com.edgenius.wiki.render.impl.LinkReplacerFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    LinkModel link = getLinkModel(result, context.getCurrentRegion());
    LinkReplacer replacer = (LinkReplacer) context.getGlobalParam(LinkReplacer.class.getName());

    if (replacer.getType() == WikiConstants.AUTO_FIX_COPY_LINK) {
        //change spaceUname: append @spaceUname after link
        if (StringUtils.isBlank(link.getSpaceUname())
                || StringUtils.equals(link.getSpaceUname(), replacer.getFromSpaceUname())) {
            buffer.append(getLink(replacer.getFromSpaceUname(), link));
            return;
        }/*ww  w.  ja v a  2  s .co m*/
    } else if (replacer.getType() == WikiConstants.AUTO_FIX_TITLE_CHANGE_LINK) {
        //change pageTitle: change old title to new one

        //link has not assign space, then from(content's space) must be same with the space of updated title page 
        if (((StringUtils.isBlank(link.getSpaceUname())
                && StringUtils.equalsIgnoreCase(replacer.getFromSpaceUname(), replacer.getToSpaceUname()))
                //if assigned space, then it must be same with the space of updated title page
                || StringUtils.equalsIgnoreCase(link.getSpaceUname(), replacer.getToSpaceUname()))
                //title must be same
                && StringUtils.equalsIgnoreCase(StringUtils.trim(link.getLink()),
                        StringUtils.trim(replacer.getOldTitle()))) {
            link.setLink(replacer.getNewTitle());
            buffer.append(getLink(null, link));
            return;
        }
    }

    String body;
    //append original text if no change
    if (context.getCurrentRegion() != null) {
        body = context.getCurrentRegion().getBody();
    } else {
        body = result.group(0);
    }

    buffer.append(body);

}

From source file:org.apache.flink.table.runtime.functions.SqlFunctionUtils.java

/**
 * Returns a string extracted with a specified regular expression and a regex
 * match group index./*from ww  w.  j ava 2 s.  c om*/
 */
public static String regexpExtract(String str, String regex, int extractIndex) {
    if (extractIndex < 0) {
        return null;
    }

    try {
        Matcher m = REGEXP_PATTERN_CACHE.get(regex).matcher(str);
        if (m.find()) {
            MatchResult mr = m.toMatchResult();
            return mr.group(extractIndex);
        }
        return null;
    } catch (Exception e) {
        LOG.error(String.format("Exception in regexpExtract('%s', '%s', '%d')", str, regex, extractIndex), e);
        return null;
    }
}