Example usage for java.lang String subSequence

List of usage examples for java.lang String subSequence

Introduction

In this page you can find the example usage for java.lang String subSequence.

Prototype

public CharSequence subSequence(int beginIndex, int endIndex) 

Source Link

Document

Returns a character sequence that is a subsequence of this sequence.

Usage

From source file:com.moviejukebox.scanner.artwork.FanartScanner.java

public static boolean scan(MovieImagePlugin backgroundPlugin, Jukebox jukebox, Movie movie) {
    String localFanartBaseFilename = movie.getBaseFilename();
    String parentPath = FileTools.getParentFolder(movie.getFile());

    // Look for the videoname.fanartToken.Extension
    String fullFanartFilename = StringTools.appendToPath(parentPath, localFanartBaseFilename + FANART_TOKEN);
    File localFanartFile = FileTools.findFileFromExtensions(fullFanartFilename, FANART_SCANNER_EXT);
    boolean foundLocalFanart = localFanartFile.exists();

    // Try searching the fileCache for the filename.
    if (!foundLocalFanart) {
        Boolean searchInJukebox = Boolean.TRUE;
        // if the fanart URL is invalid, but the fanart filename is valid, then this is likely a recheck, so don't search on the jukebox folder
        if (StringTools.isNotValidString(movie.getFanartURL())
                && StringTools.isValidString(movie.getFanartFilename())) {
            searchInJukebox = Boolean.FALSE;
        }/*from   w w  w  . j  a  v  a 2  s . co m*/
        localFanartFile = FileTools.findFilenameInCache(localFanartBaseFilename + FANART_TOKEN,
                FANART_SCANNER_EXT, jukebox, searchInJukebox);
        if (localFanartFile != null) {
            foundLocalFanart = true;
        }
    }

    // if no fanart has been found, try the foldername.fanartToken.Extension
    if (!foundLocalFanart) {
        localFanartBaseFilename = FileTools.getParentFolderName(movie.getFile());

        // Checking for the MovieFolderName.*
        fullFanartFilename = StringTools.appendToPath(parentPath, localFanartBaseFilename + FANART_TOKEN);
        localFanartFile = FileTools.findFileFromExtensions(fullFanartFilename, FANART_SCANNER_EXT);
        foundLocalFanart = localFanartFile.exists();
    }

    // Check for fanart.* and background.* fanart.
    if (!foundLocalFanart && USE_FOLDER_IMAGE) {
        // Check for each of the farnartImageName.* files
        for (String fanartFilename : IMAGE_NAMES) {
            fullFanartFilename = StringTools.appendToPath(parentPath, fanartFilename);
            localFanartFile = FileTools.findFileFromExtensions(fullFanartFilename, FANART_SCANNER_EXT);
            foundLocalFanart = localFanartFile.exists();

            if (!foundLocalFanart && movie.isTVShow()) {
                // Get the parent directory and check that
                fullFanartFilename = StringTools.appendToPath(
                        FileTools.getParentFolder(movie.getFile().getParentFile().getParentFile()),
                        fanartFilename);
                localFanartFile = FileTools.findFileFromExtensions(fullFanartFilename, FANART_SCANNER_EXT);
                foundLocalFanart = localFanartFile.exists();
                if (foundLocalFanart) {
                    break; // We found the artwork so quit the loop
                }
            } else {
                break; // We found the artwork so quit the loop
            }
        }
    }

    // Check file attachments
    if (!foundLocalFanart) {
        localFanartFile = AttachmentScanner.extractAttachedFanart(movie);
        foundLocalFanart = (localFanartFile != null);
    }

    // If we've found the fanart, copy it to the jukebox, otherwise download it.
    if (foundLocalFanart && (localFanartFile != null)) {
        fullFanartFilename = localFanartFile.getAbsolutePath();
        LOG.debug("File {} found", fullFanartFilename);

        if (StringTools.isNotValidString(movie.getFanartFilename())) {
            movie.setFanartFilename(movie.getBaseFilename() + FANART_TOKEN + "."
                    + FileTools.getFileExtension(localFanartFile.getName()));
        }

        if (StringTools.isNotValidString(movie.getFanartURL())) {
            movie.setFanartURL(localFanartFile.toURI().toString());
        }
        String fanartFilename = movie.getFanartFilename();
        String finalDestinationFileName = StringTools.appendToPath(jukebox.getJukeboxRootLocationDetails(),
                fanartFilename);
        String destFileName = StringTools.appendToPath(jukebox.getJukeboxTempLocationDetails(), fanartFilename);

        File finalDestinationFile = FileTools.fileCache.getFile(finalDestinationFileName);
        File fullFanartFile = new File(fullFanartFilename);

        // Local Fanart is newer OR ForceFanartOverwrite OR DirtyFanart
        // Can't check the file size because the jukebox fanart may have been re-sized
        // This may mean that the local art is different to the jukebox art even if the local file date is newer
        if (FileTools.isNewer(fullFanartFile, finalDestinationFile) || FANART_OVERWRITE
                || movie.isDirty(DirtyFlag.FANART)) {
            try {
                BufferedImage fanartImage = GraphicTools.loadJPEGImage(fullFanartFile);
                if (fanartImage != null) {
                    fanartImage = backgroundPlugin.generate(movie, fanartImage, "fanart", null);
                    if (PropertiesUtil.getBooleanProperty("fanart.perspective", Boolean.FALSE)) {
                        destFileName = destFileName.subSequence(0, destFileName.lastIndexOf('.') + 1) + "png";
                        movie.setFanartFilename(destFileName);
                    }
                    GraphicTools.saveImageToDisk(fanartImage, destFileName);
                    LOG.debug("{} has been copied to {}", fullFanartFilename, destFileName);
                } else {
                    movie.setFanartFilename(Movie.UNKNOWN);
                    movie.setFanartURL(Movie.UNKNOWN);
                }
            } catch (IOException ex) {
                LOG.debug("Failed loading fanart: {} - {}", fullFanartFilename, ex.getMessage());
            }
        } else {
            LOG.debug("{} already exists", finalDestinationFileName);
        }
    } else {
        LOG.debug("No local Fanart found for {} attempting to download", movie.getBaseFilename());
        checkFanartUrl(movie);
        downloadFanart(backgroundPlugin, jukebox, movie);
    }

    return foundLocalFanart;
}

From source file:org.sugarcrm.voodoodriver.Reporter.java

private void _log(String msg) {
    Date now = new Date();
    String frac = String.format("%1$tN", now);
    String date_str = String.format("%1$tm/%1$td/%1$tY-%1$tI:%1$tM:%1$tS", now);

    frac = frac.subSequence(0, 3).toString();
    date_str += String.format(".%s", frac);

    msg = replaceLineFeed(msg);/*from   w w w.j  a va  2  s . c  om*/
    String logstr = "[" + date_str + "]" + msg + this.LineSeparator;

    if (msg.isEmpty()) {
        msg = "Found empty message!";
    }

    System.out.printf("%s\n", msg);

    try {
        this.reportFD.write(logstr.getBytes());
    } catch (java.io.IOException e) {
        System.err.println("(!)Error writing to report file: " + e);
    }
}

From source file:org.sugarcrm.voodoodriver.Reporter.java

/**
 * Instantiate a Reporter object.//from  w  w w .  j a va  2 s  .  c  o  m
 *
 * @param reportName
 * @param resultDir
 */

public Reporter(String reportName, String resultDir, VDDHash config) {
    Date now = new Date();
    String frac = String.format("%1$tN", now);
    String date_str = String.format("%1$tm-%1$td-%1$tY-%1$tI-%1$tM-%1$tS", now);
    frac = frac.subSequence(0, 3).toString();
    date_str += String.format("-%s", frac);

    this.LineSeparator = System.getProperty("line.separator");

    if (resultDir != null) {
        File dir = new File(resultDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        this.resultDir = resultDir;
    } else {
        this.resultDir = System.getProperty("user.dir");
    }

    reportLog = this.resultDir + "/" + reportName + "-" + date_str + ".log";
    reportLog = FilenameUtils.separatorsToSystem(reportLog);
    System.out.printf("ReportFile: %s\n", reportLog);

    try {
        reportFD = new FileOutputStream(reportLog);
    } catch (java.io.FileNotFoundException e) {
        System.err.println("(!)Unable to create report file: " + e);
    }

    /* Initialize screenshot and savehtml events */
    String ssEvents[] = { "warning", "error", "assertfail", "exception", "watchdog" };
    this.saveHtmlOn = new VDDHash();
    this.screenshotOn = new VDDHash();
    for (String ssEvent : ssEvents) {
        this.saveHtmlOn.put(ssEvent, false);
        this.screenshotOn.put(ssEvent, false);
    }

    this.haltOnFailure = (Boolean) config.get("haltOnFailure");
}

From source file:com.cqupt.pedometer.main.UartService.java

/**
 * ???/*from   ww w . j a  v a 2 s .  c o  m*/
 *
 * @param action
 * @param characteristic
 */
private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (TX_CHAR_UUID.equals(characteristic.getUuid())) {

        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%X ", byteChar));
            String a = stringBuilder.toString();
            a = a.replaceAll("[^0-9a-zA-Z]", "");
            // String.subSequence(beginIndex, endIndex?)
            String b = (String) a.subSequence(0, 1);
            // ?
            String c = a.substring(1, a.length());
            // Integer.parseInt(s, radix) radix10101616
            int i = Integer.parseInt(c, 16);
            intent.putExtra(EXTRA_DATA, i + "");
            intent.putExtra(SAFE_DATA, b);
        }

    } else if (RX_CHAR_UUID.equals(characteristic.getUuid())) {
        intent.putExtra(CHAR1_DATA,
                "" + characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));

    } else if (Battery_Level_UUID.equals(characteristic.getUuid())) {
        intent.putExtra(EXTRA_DATA,
                "" + characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));
    }
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

From source file:org.elasticsoftware.elasterix.server.AbstractSipTest.java

protected boolean startsWith(String input, String startsWith) {
    input = input.trim();//from  ww w.ja  v a  2s  .  com
    startsWith = startsWith.trim();

    if (input.length() < startsWith.length()) {
        System.err.println(String.format("Length input to short. input[%d] != startsWith[%d]", input.length(),
                startsWith.length()));
        return false;
    }
    for (int i = 0; i < input.length(); i++) {
        if (input.charAt(i) != startsWith.charAt(i)) {
            System.err.println(String.format("Characters differ. Index[%d]. \n%s\n======\n%s", i,
                    input.subSequence(0, i), startsWith.subSequence(0, i)));
            return false;
        }
    }
    return true;
}

From source file:dev.drsoran.moloko.fragments.ChangeTagsFragment.java

private void updateTagList() {
    chosenTags.clear();//w  w w  .ja va 2  s.  c om

    String content = UIUtils.getTrimmedText(editView);

    // Remove , at the end of line
    content = content.replaceFirst("\\,\\s*$", Strings.EMPTY_STRING);

    // Remove empty tags
    content = content.replaceAll("\\,\\s*\\,", "\\,");

    final int length = content.length();
    int posStart = 0;

    // Tokenize all entries.
    while (posStart < length) {
        final int posEnd = tokenizer.findTokenEnd(content, posStart);

        chosenTags.add(content.subSequence(posStart, posEnd).toString().trim());
        posStart = posEnd + 1;
    }

    // Duplicates will be filtered out
    ensureUniqueTags();

    final List<String> allTags = getAllTagsAssertNotNull();
    final List<ChangeTag> changeTags = new ArrayList<ChangeTag>(chosenTags.size() + allTags.size());

    for (String tag : chosenTags)
        changeTags.add(new ChangeTag(tag, false));

    final List<String> unusedTags = new LinkedList<String>(allTags);
    unusedTags.removeAll(chosenTags);

    for (String tag : unusedTags)
        changeTags.add(new ChangeTag(tag, true));

    tagsList.setAdapter(
            new ChangeTagsAdapter(getSherlockActivity(), R.layout.change_tags_fragment_listitem, changeTags));
}

From source file:com.epam.reportportal.extension.bugtracking.jira.JiraStrategy.java

/**
 * Parse ticket description and find binary data
 *
 * @param issueInput/* w ww .j a v a2 s.c om*/
 * @return
 */
private Map<String, String> findBinaryData(IssueInput issueInput) {
    Map<String, String> binary = new HashMap<>();
    String description = issueInput.getField(IssueFieldId.DESCRIPTION_FIELD.id).getValue().toString();
    if (null != description) {
        // !54086a2c3c0c7d4446beb3e6.jpg| or [^54086a2c3c0c7d4446beb3e6.xml]
        String regex = "(!|\\[\\^).{24}.{0,5}(\\||\\])";
        Matcher matcher = Pattern.compile(regex).matcher(description);
        while (matcher.find()) {
            String rawValue = description.subSequence(matcher.start(), matcher.end()).toString();
            String binaryDataName = rawValue.replace("!", "").replace("[", "").replace("]", "").replace("^", "")
                    .replace("|", "");
            String binaryDataId = binaryDataName.split("\\.")[0];
            binary.put(binaryDataId, binaryDataName);
        }
    }
    return binary;
}

From source file:com.netcrest.pado.tools.pado.command.rm.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void run(CommandLine commandLine, String command) throws Exception {
    String path = commandLine.getOptionValue("path");
    String bufferName = commandLine.getOptionValue("buffer");
    List<String> argList = commandLine.getArgList();

    if (path != null && bufferName != null) {
        PadoShell.printlnError(this, "Specifying both path and buffer not allowed. Only one option allowed.");
        return;/*  w w  w  .  j av a2  s . c  o m*/
    }
    if (path == null && bufferName == null) {
        path = padoShell.getCurrentPath();
    }

    if (path != null) {

        if (commandLine.getArgList().size() < 2) {
            PadoShell.printlnError(this, "Invalid command. Key or key fields must be specified.");
            return;
        }
        String input = (String) commandLine.getArgList().get(1);
        Object key = null;
        if (input.startsWith("'")) {
            int lastIndex = -1;
            if (input.endsWith("'") == false) {
                lastIndex = input.length();
            } else {
                lastIndex = input.lastIndexOf("'");
            }
            if (lastIndex <= 1) {
                PadoShell.printlnError(this, "Invalid key. Empty string not allowed.");
                return;
            }
            key = input.subSequence(1, lastIndex); // lastIndex exclusive
        } else {
            key = ObjectUtil.getPrimitive(padoShell, input, false);
            if (key == null) {
                key = padoShell.getQueryKey(argList, 1);
            }
        }
        if (key == null) {
            return;
        }

        String fullPath = padoShell.getFullPath(path);
        String gridPath = GridUtil.getChildPath(fullPath);
        String gridId = SharedCache.getSharedCache().getGridId(fullPath);
        IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IGridMapBiz.class, gridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
        gridMapBiz.remove(key);

    } else {
        // Get key from the buffer
        BufferInfo bufferInfo = SharedCache.getSharedCache().getBufferInfo(bufferName);
        if (bufferInfo == null) {
            PadoShell.printlnError(this, bufferName + ": Buffer undefined.");
            return;
        }
        String gridId = bufferInfo.getGridId();
        String gridPath = bufferInfo.getGridPath();
        if (gridId == null || gridPath == null) {
            PadoShell.printlnError(this, bufferName + ": Invalid buffer. This buffer does not contain keys.");
            return;
        }
        if (argList.size() == 1) {
            PadoShell.printlnError(this, bufferName + ": Buffer number(s) not specified.");
            return;
        }
        Map<Integer, Object> keyMap = bufferInfo.getKeyMap(argList, 1);
        if (keyMap.size() > 0) {
            IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                    .newInstance(IGridMapBiz.class, gridPath);
            gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
            gridMapBiz.removeAll(keyMap.values());
            bufferInfo.getRemovedRowNumberSet().addAll(keyMap.keySet());
        }
    }
}

From source file:net.bible.service.format.osistohtml.NoteAndReferenceHandler.java

/** create a link tag from an OSISref and the content of the tag
 *///from   w  w w  .  ja v a2  s  .  com
private String getReferenceTag(String reference, String content) {

    StringBuilder result = new StringBuilder();
    try {

        //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out
        //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs
        // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa
        if (reference == null && content != null && content.length() > 0
                && StringUtils.isNumeric(content.subSequence(0, 1))
                && (content.length() < 2 || !StringUtils.isAlphaSpace(content.subSequence(1, 2)))) {

            // maybe should use VerseRangeFactory.fromstring(orig, basis)
            // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix
            int firstColonPos = content.indexOf(":");
            boolean isVerseAndChapter = firstColonPos > 0 && firstColonPos < 4;
            if (isVerseAndChapter) {
                reference = parameters.getBasisRef().getBook().getOSIS() + " " + content;
            } else {
                reference = parameters.getBasisRef().getBook().getOSIS() + " "
                        + parameters.getBasisRef().getChapter() + ":" + content;
            }
            log.debug("Patched reference:" + reference);
        } else if (reference == null) {
            reference = content;
        }

        Passage ref = (Passage) PassageKeyFactory.instance().getKey(reference);
        boolean isSingleVerse = ref.countVerses() == 1;
        boolean isSimpleContent = content.length() < 3 && content.length() > 0;
        Iterator<Key> it = ref.rangeIterator(RestrictionType.CHAPTER);

        if (isSingleVerse && isSimpleContent) {
            // simple verse no e.g. 1 or 2 preceding the actual verse in TSK
            result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                    .append(it.next().getOsisRef()).append("'>");
            result.append(content);
            result.append("</a>");
        } else {
            // multiple complex references
            boolean isFirst = true;
            while (it.hasNext()) {
                Key key = it.next();
                if (!isFirst) {
                    result.append(" ");
                }
                result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                        .append(key.iterator().next().getOsisRef()).append("'>");
                result.append(key);
                result.append("</a>&nbsp; ");
                isFirst = false;
            }
        }
    } catch (Exception e) {
        log.error("Error parsing OSIS reference:" + reference, e);
        // just return the content with no html markup
        result.append(content);
    }
    return result.toString();
}

From source file:org.codehaus.groovy.grails.web.pages.Parse.java

private void pageImport(String value) {
    //      LOG.debug("pageImport(" + value + ')');
    String[] imports = Pattern.compile(";").split(value.subSequence(0, value.length()));
    for (int ix = 0; ix < imports.length; ix++) {
        out.print("import ");
        out.print(imports[ix]);// w  w w  .j  ava 2 s. c  o m
        out.println();
    }
}