Example usage for java.util.regex Matcher groupCount

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

Introduction

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

Prototype

public int groupCount() 

Source Link

Document

Returns the number of capturing groups in this matcher's pattern.

Usage

From source file:fr.msch.wissl.server.Library.java

private Song getSong(File mp3, String hash) throws IOException {
    Song song = new Song();
    Album album = new Album();
    Artist artist = new Artist();

    AudioFile af = null;//from ww  w.  j a  v a2 s  . c o m
    try {
        af = AudioFileIO.read(mp3);
    } catch (Throwable e) {
        throw new IOException(e);
    }
    Tag tag = af.getTag();

    if (tag == null) {
        Logger.warn("No tag for file " + mp3.getAbsolutePath());
        song.title = "";
        song.position = 0;
        album.date = "";
        artist.name = "";
    } else {
        song.title = tag.getFirst(FieldKey.TITLE);
        String pos = tag.getFirst(FieldKey.TRACK);
        Matcher mat = positionPattern.matcher(pos);
        if (mat.matches() && mat.groupCount() == 1) {
            song.position = Integer.parseInt(mat.group(1));
        }
        album.date = tag.getFirst(FieldKey.YEAR);
        if (!album.date.matches("[0-9]{4}")) {
            album.date = "";
        }
        album.name = tag.getFirst(FieldKey.ALBUM);
        album.genre = tag.getFirst(FieldKey.GENRE);
        if (album.genre.length() > 63) {
            album.genre = album.genre.substring(0, 63);
        }
        if (album.genre.matches("[(][0-9]+[)]")) {
            int genreId = Integer.parseInt(album.genre.substring(1, album.genre.length() - 1));
            album.genre = GenreTypes.getInstanceOf().getValueForId(genreId);
        }

        String discNo = tag.getFirst(FieldKey.DISC_NO);
        if (discNo != null && discNo.trim().length() > 0) {
            mat = positionPattern.matcher(discNo);
            if (mat.matches() && mat.groupCount() == 1) {
                song.disc_no = Integer.parseInt(mat.group(1));
            }
            try {
                song.disc_no = Integer.parseInt(discNo);
            } catch (Throwable t) {
            }
        }

        artist.name = tag.getFirst(FieldKey.ALBUM_ARTIST);
        if (artist.name == null || artist.name.trim().length() == 0) {
            artist.name = tag.getFirst(FieldKey.ARTIST);
        }

        Map<String, String> art = artworks.get(artist.name);
        boolean hasArt = (art != null && art.containsKey(album.name));
        if (!hasArt) {
            File artwork = null;
            Artwork at = tag.getFirstArtwork();

            String fileName = artist.name.replaceAll("/|\\\\|\\?", "_") + "___"
                    + album.name.replaceAll("/|\\\\|\\?", "_");

            // tag exists and may contain artwork
            if (at != null) {
                artwork = new File(Config.getArtworkPath() + File.separatorChar + fileName);
                // artwork may already exist from previous run / song
                if (!artwork.exists()) {

                    byte[] img = null;
                    String url = null;
                    try {
                        img = at.getBinaryData();
                    } catch (Throwable t) {
                        // the tag reading lib can throws funny stuff
                        Logger.warn("Failed to read image in " + mp3.getAbsolutePath(), t);
                    }
                    try {
                        url = at.getImageUrl();
                    } catch (Throwable t) {
                        Logger.warn("Failed to read image url in " + mp3.getAbsolutePath(), t);
                    }

                    if (url != null && url.trim().length() > 0) {
                        Logger.info("GOT URL " + url);
                    }

                    // found image in tag... best case scenario
                    if (img != null) {
                        FileOutputStream fos = new FileOutputStream(artwork);
                        fos.write(img);
                        fos.close();
                    }
                }
            }

            // no tag, take a semi-random file in folder
            if (artwork == null || !artwork.exists()) {
                artwork = null;
                // search inside current directory
                File dir = mp3.getParentFile();
                File[] matches = dir.listFiles(artworkFilter);
                if (matches.length > 0) {
                    File dest = new File(Config.getArtworkPath() + File.separatorChar + fileName);
                    FileUtils.copyFile(matches[0], dest);
                    artwork = dest;
                } else {
                    // take first image in folder! probably wrong..
                    matches = dir.listFiles(artworkFallback);
                    if (matches.length > 0) {
                        File dest = new File(Config.getArtworkPath() + File.separatorChar + fileName);
                        FileUtils.copyFile(matches[0], dest);
                        artwork = dest;
                    } else {
                        // no artwork found...
                        artwork = null;
                    }
                }
            }
            if (artwork != null && artwork.exists()) {
                Map<String, String> m = artworks.get(artist.name);
                if (m == null) {
                    m = new ConcurrentHashMap<String, String>();
                    artworks.put(artist.name, m);
                }
                if (!m.containsKey(album.name)) {
                    m.put(album.name, artwork.getAbsolutePath());
                }
            }
        }
    }

    song.filepath = mp3.getAbsolutePath();
    song.hash = hash;
    song.album = album;
    song.artist = artist;
    song.filepath = mp3.getAbsolutePath();
    song.duration = af.getAudioHeader().getTrackLength();
    song.hash = hash;
    song.album_name = album.name;
    song.artist_name = artist.name;
    album.artist_name = artist.name;

    String format = af.getAudioHeader().getEncodingType();
    if ("mp3".equalsIgnoreCase(format)) {
        song.format = "audio/mpeg";
    } else if ("aac".equalsIgnoreCase(format)) {
        song.format = "audio/aac";
    } else if (format.toLowerCase().startsWith("ogg")) {
        song.format = "audio/ogg";
    } else {
        // maybe FLAC and WAV re not unknown,
        // but they make little sense over a streaming server.
        // maybe when there is transcoding we'll see about it..
        throw new IOException("Unknown format: " + format);
    }

    if (song.title.trim().isEmpty()) {
        song.title = mp3.getName();
    }
    if (artist.name.trim().isEmpty()) {
        artist.name = "";
    }
    if (album.name.trim().isEmpty()) {
    }

    return song;
}

From source file:controller.FacebookServlet.java

public boolean doFilePost64(HttpServletRequest request) throws FacebookDAOException {
    System.out.println("Do file post 45");
    if (request.getContentType() == null) {
        System.out.println("Content type null");
        return false;
    }/* ww w .j a  v a  2  s .  c  om*/

    String s = null;
    try {
        ServletInputStream input = request.getInputStream();
        s = IOUtils.toString(input);
        Pattern regex = Pattern
                .compile("name=(.*)&email=(.*)&password=(.*)&birthday=(.*)&profile=(.*)&cover=(.*)");
        Matcher m = regex.matcher(s);
        if (m.find() && m.groupCount() > 0) {
            String name = m.group(1);
            String email = m.group(2);
            String password = m.group(3);
            String birthday = m.group(4);
            String profile = m.group(5);
            String cover = m.group(6);
            System.out.println(name + " - " + email + " - " + password + " - " + birthday);//+" - "+profile);//+" - "+cover);
            System.out.println(profile.length());
            //
            //
            System.out.println("CALENDAR");
            Calendar birth = Calendar.getInstance();
            System.out.println("DATE");
            String date[] = (birthday.split("-"));
            System.out.println("BIRTH" + birthday);
            birth.set(Integer.valueOf(date[0]), Integer.valueOf(date[1]), Integer.valueOf(date[2]));
            //System.out.println(birth);
            System.out.println("USER");
            User u = new User(name, email, birth);
            //System.out.println(u);
            String pathFile = "C:/Users/BBEIRIGO/Documents/NetBeansProjects/WebServiceFacebook/src/main/webapp/";
            FacebookDAO dao = new FacebookDAO(pathFile);
            User cadastrado = dao.saveUser(u, password);
            new File(pathFile + "/photos/" + cadastrado.getId() + "/Cover").mkdirs();
            new File(pathFile + "/photos/" + cadastrado.getId() + "/Profile").mkdirs();
            System.out.println(cadastrado);
            System.out.println("cover:" + cadastrado.getCoverPhoto().getPath());
            ///
            String coverPath = cadastrado.getCoverPhoto().getPath();
            String profilePath = cadastrado.getProfilePhoto().getPath();
            System.out.println(coverPath);
            //                if (saveFileEconded(URLDecoder.decode(cover, "UTF-8"), coverPath)) {
            //                    System.out.println("ENCODE COVER!!!");
            //                } else {
            //                    System.out.println("NO ENCODE COVER!!!");
            //                }
            //                if (saveFileEconded(URLDecoder.decode(profile, "UTF-8"), profilePath)) {
            //                    System.out.println("ENCODE PROFILE!!!");
            //                } else {
            //                    System.out.println("NO ENCODE PROFILE!!!");
            //                }
        } else {
            System.out.println("No achou!");
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}

From source file:org.apache.openaz.xacml.pdp.test.policy.TestPolicy.java

protected void removeRequests() {
    ///*  w  w w  .  j  a v  a  2  s  .co m*/
    // Delete any existing request files that we generate. i.e. Have the Unknown in the file name.
    //
    try {
        Files.walkFileTree(Paths.get(this.directory.toString(), "requests"), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                //
                // Sanity check the file name
                //
                Matcher matcher = pattern.matcher(file.getFileName().toString());
                if (matcher.matches()) {
                    try {
                        //
                        // Pull what this request is supposed to be
                        //
                        String group = null;
                        int count = matcher.groupCount();
                        if (count >= 1) {
                            group = matcher.group(count - 1);
                        }
                        //
                        // Send it
                        //
                        if (group.equals("Unknown")) {
                            //
                            // Remove the file
                            //
                            Files.delete(file);
                        }
                    } catch (Exception e) {
                        logger.error(e);
                        e.printStackTrace();
                    }
                }
                return super.visitFile(file, attrs);
            }
        });
    } catch (IOException e) {
        logger.error("Failed to removeRequests from " + this.directory + " " + e);
    }
}

From source file:by.stub.yaml.stubs.StubRequest.java

private boolean regexMatch(final String dataStoreValue, final String thisAssertingValue,
        final String templateTokenName) {
    try {/*from  ww  w  .ja  v a 2s .  com*/
        // Pattern.MULTILINE changes the behavior of '^' and '$' characters,
        // it does not mean that newline feeds and carriage return will be matched by default
        // You need to make sure that you regex pattern covers both \r (carriage return) and \n (linefeed).
        // It is achievable by using symbol '\s+' which covers both \r (carriage return) and \n (linefeed).
        final Matcher matcher = Pattern.compile(dataStoreValue, Pattern.MULTILINE).matcher(thisAssertingValue);
        final boolean isMatch = matcher.matches();
        if (isMatch) {
            // group(0) holds the full regex match
            regexGroups.put(StringUtils.buildToken(templateTokenName, 0), matcher.group(0));

            //Matcher.groupCount() returns the number of explicitly defined capturing groups in the pattern regardless
            // of whether the capturing groups actually participated in the match. It does not include matcher.group(0)
            final int groupCount = matcher.groupCount();
            if (groupCount > 0) {
                for (int idx = 1; idx <= groupCount; idx++) {
                    regexGroups.put(StringUtils.buildToken(templateTokenName, idx), matcher.group(idx));
                }
            }
        }
        return isMatch;
    } catch (PatternSyntaxException e) {
        return dataStoreValue.equals(thisAssertingValue);
    }
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

public Map<String, Comparable<?>> executeAutoitFile(String fullPath, String workDir, String autoItLocation,
        int timeout, Vector<Object> params) {

    Exception threwOne = null;//from ww w . j av a  2 s.c  om
    Hashtable<String, Comparable<?>> result = new Hashtable<String, Comparable<?>>();
    File sfile = new File(fullPath);
    if (!sfile.exists()) {
        System.out.println(agentWorkDir.getAbsolutePath());
        System.out.println("Couldn't find " + sfile);
        return result;
    }
    Command cmd = new Command();
    cmd.setTimeout(timeout);

    String[] commandParams = new String[3 + params.size()];
    commandParams[0] = getAutoExecuterItLocation(autoItLocation);
    ;
    commandParams[1] = "/ErrorStdOut";
    commandParams[2] = sfile.getAbsolutePath();

    Log.info("Parameters:\n");
    for (int index = 0; index < params.size(); index++) {
        Log.info(params.get(index).toString() + NEW_LINE);
        commandParams[index + 3] = params.get(index).toString();
    }

    cmd.setCmd(commandParams);
    File workingDirectory = new File(workDir);
    cmd.setDir(workingDirectory.exists() ? workingDirectory : agentWorkDir);

    try {
        Execute.execute(cmd, true);
    } catch (Exception e) {
        threwOne = e;
    }

    Log.info(" \n");
    Log.info(" \n");

    String scriptText = "";
    try {
        scriptText = FileUtils.read(sfile);
        Pattern pattern = Pattern.compile("^Local \\$var = ([\\w\\d\\p{Punct} ]+)$", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(scriptText);
        if (matcher.find()) {
            Log.info("AutoIt Command : " + matcher.group(matcher.groupCount()) + NEW_LINE);
        }
    } catch (IOException ioException) {
        Log.throwable(ioException.getMessage(), ioException);
    }
    String stdoutText = cmd.getStdout().toString();
    int returnCodeValue = cmd.getReturnCode();
    String stderrText = cmd.getStderr().toString();

    if (isUseScreenShot || threwOne != null || !stderrText.isEmpty()) {
        String windowName = UUID.randomUUID().toString();
        new ScreenShotThread(windowName).start();
        Log.infoLog("A screenshot with the uuid : " + windowName + NEW_LINE);
    }

    Log.messageLog(SCRIPT + ":\n" + scriptText + NEW_LINE);
    Log.messageLog(STDOUT + ":\n" + stdoutText + NEW_LINE);
    Log.messageLog(RETURN + ":\n" + returnCodeValue + NEW_LINE);
    Log.messageLog(STDERR + ":\n" + stderrText + NEW_LINE);

    result.put(SCRIPT, scriptText);
    result.put(STDOUT, stdoutText);
    result.put(RETURN, returnCodeValue);
    result.put(STDERR, stderrText);

    if (isDebug) {
        if (isAutoDeleteFiles) {
            HistoryFile.addFile(sfile);
            Log.infoLog("Adding " + sfile.getAbsolutePath() + " to \"For deletion files list\"\n");
        }
    } else {
        sfile.deleteOnExit();
    }

    return result;
}

From source file:org.apache.kylin.monitor.ApiRequestParser.java

public void parseRequestLog(String filePath, String dPath) throws ParseException, IOException {

    logger.info("Start parsing kylin api request file " + filePath + " !");

    // writer config init
    FileSystem fs = this.getHdfsFileSystem();
    org.apache.hadoop.fs.Path resultStorePath = new org.apache.hadoop.fs.Path(dPath);
    OutputStreamWriter writer = new OutputStreamWriter(fs.append(resultStorePath));
    CSVWriter cwriter = new CSVWriter(writer, '|', CSVWriter.NO_QUOTE_CHARACTER);

    Pattern p_available = Pattern.compile("/kylin/api/(cubes|user)+.*");
    Pattern p_request = Pattern.compile(
            "^.*\\[.*KylinApiFilter.logRequest.*\\].*REQUEST:.*REQUESTER=(.*);REQ_TIME=(\\w+ (\\d{4}-\\d{2}-\\d{2}).*);URI=(.*);METHOD=(.*);QUERY_STRING=(.*);PAYLOAD=(.*);RESP_STATUS=(.*);$");
    Pattern p_uri = Pattern.compile("/kylin/api/(\\w+)(/.*/)*(.*)$");
    Matcher m_available = p_available.matcher("");
    Matcher m_request = p_request.matcher("");
    Matcher m_uri = p_uri.matcher("");

    Path path = Paths.get(filePath);
    try {//from   w  w  w. ja  v a2s  .  c om
        BufferedReader reader = Files.newBufferedReader(path, ENCODING);
        String line = null;
        while ((line = reader.readLine()) != null) {
            // reset the input
            m_available.reset(line);
            m_request.reset(line);

            // filter unnecessary info
            if (m_available.find()) {
                // filter GET info
                if (m_request.find() && !m_request.group(5).equals("GET")) {

                    List<String> groups = new ArrayList<String>();
                    for (int i = 1; i <= m_request.groupCount(); i++) {
                        groups.add(m_request.group(i));
                    }

                    String uri = m_request.group(4);
                    m_uri.reset(uri);
                    if (m_uri.find()) {

                        // add target
                        groups.add(m_uri.group(1));

                        // add action
                        if (m_uri.group(1).equals("cubes")) {
                            String method = m_request.group(5);
                            if ("DELETE".equals(method)) {
                                groups.add("drop");
                            } else if ("POST".equals(method)) {
                                groups.add("save");
                            } else {
                                // add parse action
                                groups.add(m_uri.group(3));
                            }
                        }
                    }
                    groups.add(DEPLOY_ENV);
                    String[] recordArray = groups.toArray(new String[groups.size()]);
                    // write to hdfs
                    cwriter.writeNext(recordArray);
                }
            }

        }
    } catch (IOException ex) {
        logger.info("Failed to write to hdfs:", ex);
    } finally {
        writer.close();
        cwriter.close();
        fs.close();
    }

    logger.info("Finish parsing file " + filePath + " !");
}

From source file:com.ephesoft.dcma.tablefinder.share.DataTableService.java

/**
 * Sets column header span for a column.
 * //from w w  w  .j  a  v a2s .  c o  m
 * @param inputData {@link String}
 * @param columnHeaderPattern {@link String}
 * @param spanList {@link List}<{@link Span}>
 * @throws DCMAApplicationException {@link DCMAApplicationException}
 */
private final DataCarrier setColumnHeaderSpan(final String inputData, final String columnHeaderPattern,
        final List<Span> spanList) throws DCMAApplicationException {
    List<Span> bestMatchSpans = null;
    String value = null;
    float bestConfidence = 0;
    Coordinates bestMatchSpanCoordinates = null;
    if (EphesoftStringUtil.isNullOrEmpty(inputData)) {
        LOGGER.warn("Invalid input character sequence of line.");
    } else {
        if (EphesoftStringUtil.isNullOrEmpty(columnHeaderPattern)) {
            LOGGER.warn("Invalid input pattern sequence.");
        } else {

            // Compile and use regular expression
            final CharSequence inputStr = inputData;
            final Pattern pattern = Pattern.compile(columnHeaderPattern);
            final Matcher matcher = pattern.matcher(inputStr);
            float previousConfidence = 0;
            final List<Coordinates> coordinatesList = new ArrayList<Coordinates>();
            while (matcher.find()) {

                // Get all groups for this match
                for (int i = 0; i <= matcher.groupCount(); i++) {
                    final String groupString = matcher.group(i);
                    if (groupString != null) {
                        final int startIndex = matcher.start();
                        final int endIndex = startIndex + groupString.trim().length();
                        List<Span> matchedSpans = PatternMatcherUtil.getMatchedSpans(spanList, startIndex,
                                endIndex);
                        String headerValue = PatternMatcherUtil.getMatchedSpansValue(matchedSpans);
                        if (!EphesoftStringUtil.isNullOrEmpty(headerValue)) {
                            final float confidence = (groupString.length()
                                    * CommonConstants.DEFAULT_MAXIMUM_CONFIDENCE) / headerValue.length();
                            LOGGER.info("Matched Value : ", groupString, " ,Confidence : ", confidence);
                            if (confidence > previousConfidence) {
                                bestMatchSpans = matchedSpans;
                                bestConfidence = confidence;
                                value = headerValue;
                                previousConfidence = confidence;
                                coordinatesList.clear();
                                for (Span span : matchedSpans) {
                                    coordinatesList.add(span.getCoordinates());
                                }
                                bestMatchSpanCoordinates = HocrUtil.getRectangleCoordinates(coordinatesList);
                            }
                            LOGGER.info(groupString);
                        }
                    }
                }
            }
        }
    }
    DataCarrier dataCarrier = new DataCarrier(bestMatchSpans, bestConfidence, value, bestMatchSpanCoordinates);
    return dataCarrier;
}

From source file:it.reply.orchestrator.service.deployment.providers.ImServiceImpl.java

protected InfrastructureManager getClient(DeploymentMessage dm) {
    IaaSType iaasType = dm.getChosenCloudProviderEndpoint().getIaasType();
    String authString = null;/*w  ww  .j  av a 2  s.com*/
    try {
        LOG.debug("Load {} credentials with: {}", iaasType, dm.getChosenCloudProviderEndpoint());
        switch (iaasType) {
        case OPENSTACK:
            // FIXME remove hardcoded string
            if (dm.getChosenCloudProviderEndpoint().getCpEndpoint().contains("recas.ba.infn")
                    || !oidcProperties.isEnabled()) {
                try (InputStream is = ctx.getResource(openstackAuthFilePath).getInputStream()) {
                    authString = IOUtils.toString(is);
                }
                if (oidcProperties.isEnabled()) {
                    authString = authString.replaceAll("InfrastructureManager; username = .+; password = .+",
                            "InfrastructureManager; token = " + dm.getOauth2Token());
                }
                authString = authString.replaceAll("\n", "\\\\n");
            } else {
                String endpoint = dm.getChosenCloudProviderEndpoint().getCpEndpoint();
                OpenstackAuthVersion authVersion = OpenstackAuthVersion.PASSWORD_2_0;
                Matcher matcher = OS_ENDPOINT_PATTERN.matcher(endpoint);
                if (!matcher.matches()) {
                    throw new DeploymentException("Wrong OS endpoint format: " + endpoint);
                } else {
                    endpoint = matcher.group(1);
                    if (matcher.groupCount() > 1 && matcher.group(2).equals("v3")) {
                        authVersion = OpenstackAuthVersion.PASSWORD_3_X;
                    }
                }
                AuthorizationHeader ah = new AuthorizationHeader();
                Credentials cred = ImCredentials.buildCredentials().withToken(dm.getOauth2Token());
                ah.addCredential(cred);
                cred = OpenStackCredentials.buildCredentials().withTenant("oidc").withUsername("indigo-dc")
                        .withPassword(dm.getOauth2Token()).withHost(endpoint).withAuthVersion(authVersion);
                ah.addCredential(cred);
                InfrastructureManager im = new InfrastructureManager(imUrl, ah);
                return im;
            }
            break;
        case OPENNEBULA:
            if (oidcProperties.isEnabled()) {
                AuthorizationHeader ah = new AuthorizationHeader();
                Credentials cred = ImCredentials.buildCredentials().withToken(dm.getOauth2Token());
                ah.addCredential(cred);
                cred = OpenNebulaCredentials.buildCredentials()
                        .withHost(dm.getChosenCloudProviderEndpoint().getCpEndpoint())
                        .withToken(dm.getOauth2Token());
                ah.addCredential(cred);
                InfrastructureManager im = new InfrastructureManager(imUrl, ah);
                return im;
            } else {
                // read onedock auth file
                try (InputStream in = ctx.getResource(opennebulaAuthFilePath).getInputStream()) {
                    authString = IOUtils.toString(in, StandardCharsets.UTF_8.toString());
                }
                authString = authString.replaceAll("\n", "\\\\n");
            }
            break;
        // inputStream = ctx.getResource(opennebulaAuthFilePath).getInputStream();
        // break;
        case AWS:
            AuthorizationHeader ah = new AuthorizationHeader();
            Credentials cred = ImCredentials.buildCredentials().withToken(dm.getOauth2Token());
            ah.addCredential(cred);
            cred = AmazonEc2Credentials.buildCredentials()
                    .withUsername(dm.getChosenCloudProviderEndpoint().getUsername())
                    .withPassword(dm.getChosenCloudProviderEndpoint().getPassword());
            ah.addCredential(cred);
            InfrastructureManager im = new InfrastructureManager(imUrl, ah);
            return im;
        default:
            throw new IllegalArgumentException(String.format("Unsupported provider type <%s>", iaasType));
        }
        InfrastructureManager im = new InfrastructureManager(imUrl, authString);
        return im;
    } catch (IOException | ImClientException ex) {
        throw new OrchestratorException("Cannot load IM auth file", ex);
    }
}

From source file:fr.logfiletoes.TailerListenerUnit.java

public void handle(String line) {
    LOG.log(Level.FINEST, "handle log: " + line);
    Matcher matcher = unit.getPattern().matcher(line);
    if (unit.getConcatPreviousPattern() != null
            && unit.getConcatPreviousPattern().matcher(line).find() == false) {
        if (sb != null) {
            sb.append("\n").append(line);
        }/*from  ww w.jav  a2 s.c  o m*/
    } else {
        if (sb != null) {
            json.put("message", sb.toString());
            json.put("host", host);
            String id = null;

            // Save StringBuilder if concat previous not null (wait stacktrace for example, no log end line)
            if (unit.getConcatPreviousPattern() != null) {
                saveToElasticsearch();
            }
        }
        sb = new StringBuilder(line);
        json = new JSONObject();
        while (matcher.find()) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
                String field = unit.getGroupToField().get(i);
                if (field != null) {
                    json.put(field, matcher.group(i));
                    // Surcharge du message
                    if ("message".equals(field)) {
                        sb = new StringBuilder(matcher.group(i));
                    }
                }
            }

            if (unit.getAddFieldToTimestamp() != null && unit.getSdf() != null
                    && unit.getFieldToTimestamp() != null) {
                String timestampFieldGroup = unit.getGroupToField().get(unit.getFieldToTimestamp());
                if (timestampFieldGroup != null) {
                    String date = json.getString(timestampFieldGroup);
                    try {
                        Date timestamp = unit.getSdf().parse(date);
                        json.put(unit.getAddFieldToTimestamp(), dateFormat.format(timestamp));
                    } catch (ParseException exception) {
                        LOG.warning("Unable to parse date \"" + date + "\" with pattern \""
                                + unit.getSdf().toPattern() + "\"");
                    }
                }
            }
        }

        // Save immediately StringBuilder if concat previous is null (no multiline log)
        if (unit.getConcatPreviousPattern() == null) {
            saveToElasticsearch();
        }

    }
}

From source file:com.app.util.browser.BrowserSniffer.java

private void sniffOS() throws Exception {
    // look for Windows Box
    // eg: Windows NT 5.0
    // [0] = Windows NT 5.0
    // [1] = Windows
    // [2] = NT/*from   w w  w .  ja v a2 s.  c  o  m*/
    // [3] = 5.0
    ArrayList matches = getMatches(WindowsPat, ua, 4);
    if (!matches.isEmpty()) {
        String[] versionParticulars = (String[]) matches.get(0);
        String v1 = versionParticulars[2];
        String v2 = versionParticulars[3];

        // Establish NT 6.0 as Windows Vista
        if (StringUtils.contains(v1, "nt") && StringUtils.equals(v2, "6.0"))
            v1 = "vista";
        // Establish NT 5.2 as Windows Server 2003 or XP 64
        else if (StringUtils.contains(v1, "nt") && StringUtils.equals(v2, "5.2"))
            v1 = "2003";
        // Establish NT 5.1 as Windows XP
        else if (StringUtils.contains(v1, "nt") && StringUtils.equals(v2, "5.1"))
            v1 = "xp";
        // Establish NT 5.0 and Windows 2000 as win2k
        else if (StringUtils.equals(v1, "2000"))
            v1 = "2000";
        else if (StringUtils.contains(v1, "nt") && StringUtils.contains(v2, "5.0"))
            v1 = "2000";
        // Establish NT 4.0 as winnt
        else if (StringUtils.contains(v1, "nt")
                && (StringUtils.contains(v2, "4.0") || StringUtils.contains(v2, "3.51")
                        || StringUtils.contains(v2, "3.5") || StringUtils.contains(v2, "3.1")))
            v1 = "nt";
        // Establish 9x 4.90 as Windows 98
        else if (StringUtils.contains(v1, "9x") && StringUtils.equals(v2, "98"))
            v1 = "98";
        // See if we're running windows 3.1
        else if (StringUtils.equals(StringUtils.join(new String[] { v1, v2 }), "16bit"))
            v1 = "31";
        // otherwise display as is (31,95,98,NT,ME,XP)
        else
            v1 = StringUtils.join(new String[] { v1, v2 });

        if (StringUtils.isEmpty(v1)) {
            final Matcher matcher = NumberRetrievePat.matcher(versionParticulars[0]);
            if (matcher.matches()) {
                v1 = matcher.group(matcher.groupCount());
                if (StringUtils.contains(versionParticulars[0], "nt"))
                    v1 = "nt";
            } else {
                v1 = PLATFORM_WIN;
            }
        }

        os = v1;
        platform = PLATFORM_WIN;
        return;
    }

    // look for amiga OS
    // eg: Amiga-AWeb/3.5.07 beta
    // [0] = Amiga
    matches = getMatches(AmigaPat, ua, 1);
    if (!matches.isEmpty()) {
        platform = PLATFORM_AMIGA;
        if (StringUtils.contains(ua, "morphos"))
            os = "morphos";
        else if (StringUtils.contains(ua, "mc680x0"))
            os = "mc680x0";
        else if (StringUtils.contains(ua, "ppc"))
            os = "ppc";
        else {
            matches = getMatches(AmigaVerPat, ua, 2);
            if (!matches.isEmpty()) {
                int count = matches.size() - 1;
                String[] versionParticulars = (String[]) matches.get(count);
                os = versionParticulars[1];
            }
        }

        return;
    }

    // look for OS2
    matches = getMatches(Os2Pat, ua, 1);
    if (!matches.isEmpty()) {
        platform = PLATFORM_OS2;
        os = PLATFORM_OS2;
        return;
    }

    // look for mac
    // sets: platform = mac ; os = 68k or ppc
    matches = getMatches(MacPat, ua, 5);
    if (!matches.isEmpty()) {
        platform = PLATFORM_MAC;

        int count = matches.size() - 1;
        String[] versionParticulars = (String[]) matches.get(count);
        os = (StringUtils.isNotEmpty(versionParticulars[1])) ? "68k" : StringUtils.EMPTY;
        os = (StringUtils.isNotEmpty(versionParticulars[2])) ? "osx" : os;
        os = (StringUtils.isNotEmpty(versionParticulars[3])) ? "osx" : os;
        os = (StringUtils.isNotEmpty(versionParticulars[4])) ? "ppc" : os;
        return;
    }

    //  look for *nix boxes
    //  sunos sets: platform = *nix ; os = sun|sun4|sun5|suni86
    matches = getMatches(SunosPat, ua, 3);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;

        int count = matches.size() - 1;
        String[] versionParticulars = (String[]) matches.get(count);
        if (!StringUtils.contains("sun", versionParticulars[1]))
            versionParticulars[1] = StringUtils.join(new String[] { "sun", versionParticulars[1] });
        os = StringUtils.join(new String[] { versionParticulars[1], versionParticulars[2] });
        return;
    }

    // irix sets: platform = *nix ; os = irix|irix5|irix6|...
    matches = getMatches(IrixPat, ua, 3);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;

        int count = matches.size() - 1;
        String[] versionParticulars = (String[]) matches.get(count);
        os = StringUtils.join(new String[] { versionParticulars[1], versionParticulars[2] });
        return;
    }

    // hp-ux sets: platform = *nix ; os = hpux9|hpux10|...
    matches = getMatches(HpuxPat, ua, 3);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;

        int count = matches.size() - 1;
        String[] versionParticulars = (String[]) matches.get(count);
        versionParticulars[1] = StringUtils.replace(versionParticulars[1], "-", StringUtils.EMPTY);
        os = StringUtils.join(new String[] { versionParticulars[1], StringUtils.trim(versionParticulars[2]) });
        return;
    }

    // aix sets: platform = *nix ; os = aix|aix1|aix2|aix3|...
    matches = getMatches(AixPat, ua, 2);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;

        int count = matches.size() - 1;
        String[] versionParticulars = (String[]) matches.get(count);
        os = StringUtils.join(new String[] { "aix", versionParticulars[1] });
        return;
    }

    // dec sets: platform = *nix ; os = dec
    matches = getMatches(DecPat, ua, 1);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;
        os = "dec";
        return;
    }

    // vms sets: platform = *nix ; os = vms
    matches = getMatches(VmsPat, ua, 1);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;
        os = "vms";
        return;
    }

    // sco sets: platform = *nix ; os = sco
    matches = getMatches(ScoPat, ua, 1);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;
        os = "sco";
        return;
    }

    // unixware sets: platform = *nix ; os = unixware
    if (StringUtils.contains(ua, "'unix_system_v'")) {
        platform = PLATFORM_UNIX;
        os = "unixware";
        return;
    }

    // mpras sets: platform = *nix ; os = mpras
    if (StringUtils.contains(ua, "'ncr'")) {
        platform = PLATFORM_UNIX;
        os = "mpras";
        return;
    }

    // reliant sets: platform = *nix ; os = reliant
    if (StringUtils.contains(ua, "'reliantunix'")) {
        platform = PLATFORM_UNIX;
        os = "reliant";
        return;
    }

    // sinix sets: platform = *nix ; os = sinix
    if (StringUtils.contains(ua, "'sinix'")) {
        platform = PLATFORM_UNIX;
        os = "sinix";
        return;
    }

    // bsd sets: platform = *nix ; os = bsd|freebsd
    matches = getMatches(BsdPat, ua, 3);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;

        int count = matches.size() - 1;
        String[] versionParticulars = (String[]) matches.get(count);
        os = StringUtils.join(new String[] { versionParticulars[1], versionParticulars[2] });
        return;
    }

    // linux sets: platform = *nix ; os = linux
    matches = getMatches(LinuxPat, ua, 1);
    if (!matches.isEmpty()) {
        platform = PLATFORM_UNIX;
        os = "linux";
        return;
    }

    platform = PLATFORM_OTHER;
    os = "unknown";
}