Example usage for org.apache.commons.lang StringUtils startsWith

List of usage examples for org.apache.commons.lang StringUtils startsWith

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils startsWith.

Prototype

public static boolean startsWith(String str, String prefix) 

Source Link

Document

Check if a String starts with a specified prefix.

Usage

From source file:org.digidoc4j.impl.bdoc.xades.XadesSignatureParserTest.java

@Test
public void parseBesSignature() throws Exception {
    XadesValidationReportGenerator xadesReportGenerator = createXadesReportGenerator(
            "testFiles/xades/test-bes-signature.xml");
    XadesSignature signature = new XadesSignatureParser().parse(xadesReportGenerator);
    assertEquals(SignatureProfile.B_BES, signature.getProfile());
    logger.debug("Getting signature id");
    assertEquals("id-693869a500c60f0dc262f7287f033d5d", signature.getId());
    logger.debug("Getting signature method");
    assertEquals("http://www.w3.org/2001/04/xmlenc#sha256", signature.getSignatureMethod());
    logger.debug("Getting signing time");
    assertEquals(new Date(1454928400000L), signature.getSigningTime());
    logger.debug("Getting city");
    assertEquals("Tallinn", signature.getCity());
    logger.debug("Getting state");
    assertEquals("Harjumaa", signature.getStateOrProvince());
    logger.debug("Getting postal code");
    assertEquals("13456", signature.getPostalCode());
    logger.debug("Getting country name");
    assertEquals("Estonia", signature.getCountryName());
    logger.debug("Getting signer roles");
    assertEquals("Manager", signature.getSignerRoles().get(0));
    assertEquals("Suspicious Fisherman", signature.getSignerRoles().get(1));
    logger.debug("Getting signing certificate");
    assertNotNull(signature.getSigningCertificate());
    logger.debug("Getting signing cert subject name");
    assertTrue(StringUtils.startsWith(signature.getSigningCertificate().issuerName(),
            "C=EE,O=AS Sertifitseerimiskeskus"));
    logger.debug("Getting signature as a byte array");
    logger.debug("Asserting null values");
    assertNull(signature.getOCSPCertificate());
    assertNull(signature.getOCSPResponseCreationTime());
    assertNull(signature.getTimeStampTokenCertificate());
    assertNull(signature.getTimeStampCreationTime());
    assertNull(signature.getTrustedSigningTime());
    logger.debug("Finished testing BES signature");
}

From source file:org.digidoc4j.impl.bdoc.xades.XadesSignatureParserTest.java

@Test
public void parseBDocTsaSignature() throws Exception {
    XadesValidationReportGenerator xadesReportGenerator = createXadesReportGenerator(
            "testFiles/xades/test-bdoc-tsa.xml");
    XadesSignature signature = new XadesSignatureParser().parse(xadesReportGenerator);
    assertEquals(SignatureProfile.LTA, signature.getProfile());
    assertEquals("id-168ef7d05729874fab1a88705b09b5bb", signature.getId());
    assertEquals("http://www.w3.org/2001/04/xmlenc#sha256", signature.getSignatureMethod());
    assertEquals(new Date(1455032287000L), signature.getSigningTime());
    assertTrue(StringUtils.startsWith(signature.getSigningCertificate().issuerName(),
            "C=EE,O=AS Sertifitseerimiskeskus"));
    assertEquals(new Date(1455032289000L), signature.getOCSPResponseCreationTime());
    assertEquals(new Date(1455032288000L), signature.getTimeStampCreationTime());
    assertEquals(signature.getTimeStampCreationTime(), signature.getTrustedSigningTime());
}

From source file:org.digidoc4j.testutils.RestrictedFileWritingRule.java

private boolean isAllowedToWrite(String file) {
    for (String prefix : whiteList) {
        if (StringUtils.startsWith(file, prefix)) {
            return true;
        }/*from w  w w  .  ja  v  a2 s. c o m*/
    }
    return false;
}

From source file:org.dspace.authority.AuthorityValueServiceImpl.java

@Override
public AuthorityValue generate(Context context, String authorityKey, String content, String field) {
    AuthorityValue nextValue = null;/*  www  .  ja  v  a 2  s .  com*/

    nextValue = generateRaw(authorityKey, content, field);

    if (nextValue != null) {
        //Only generate a new UUID if there isn't one offered OR if the identifier needs to be generated
        if (StringUtils.isBlank(authorityKey)) {
            // An existing metadata without authority is being indexed
            // If there is an exact match in the index, reuse it before adding a new one.
            List<AuthorityValue> byValue = findByExactValue(context, field, content);
            if (byValue != null && !byValue.isEmpty()) {
                authorityKey = byValue.get(0).getId();
            } else {
                authorityKey = UUID.randomUUID().toString();
            }
        } else if (StringUtils.startsWith(authorityKey, GENERATE)) {
            authorityKey = UUID.randomUUID().toString();
        }

        nextValue.setId(authorityKey);
        nextValue.updateLastModifiedDate();
        nextValue.setCreationDate(new Date());
        nextValue.setField(field);
    }

    return nextValue;
}

From source file:org.dspace.authority.indexer.DSpaceAuthorityIndexer.java

/**
 * This method looks at the authority of a metadata.
 * If the authority can be found in solr, that value is reused.
 * Otherwise a new authority value will be generated that will be indexed in solr.
 * If the authority starts with AuthorityValueGenerator.GENERATE, a specific type of AuthorityValue will be generated.
 * Depending on the type this may involve querying an external REST service
 *
 * @param metadataField Is one of the fields defined in dspace.cfg to be indexed.
 * @param value         Is one of the values of the given metadataField in one of the items being indexed.
 * @throws SQLException if database error
 * @throws AuthorizeException if authorization error
 *//*from  www.  j a  va  2  s. c o  m*/
protected void prepareNextValue(String metadataField, MetadataValue value)
        throws SQLException, AuthorizeException {

    nextValue = null;

    String content = value.getValue();
    String authorityKey = value.getAuthority();
    //We only want to update our item IF our UUID is not present or if we need to generate one.
    boolean requiresItemUpdate = StringUtils.isBlank(authorityKey)
            || StringUtils.startsWith(authorityKey, AuthorityValueService.GENERATE);

    if (StringUtils.isNotBlank(authorityKey) && !authorityKey.startsWith(AuthorityValueService.GENERATE)) {
        // !uid.startsWith(AuthorityValueGenerator.GENERATE) is not strictly necessary here but it prevents exceptions in solr
        nextValue = authorityValueService.findByUID(context, authorityKey);
    }
    if (nextValue == null && StringUtils.isBlank(authorityKey) && useCache) {
        // A metadata without authority is being indexed
        // If there is an exact match in the cache, reuse it rather than adding a new one.
        AuthorityValue cachedAuthorityValue = cache.get(content);
        if (cachedAuthorityValue != null) {
            nextValue = cachedAuthorityValue;
        }
    }
    if (nextValue == null) {
        nextValue = authorityValueService.generate(context, authorityKey, content,
                metadataField.replaceAll("\\.", "_"));
    }
    if (nextValue != null && requiresItemUpdate) {
        nextValue.updateItem(context, currentItem, value);
        try {
            itemService.update(context, currentItem);
        } catch (Exception e) {
            log.error("Error creating a metadatavalue's authority", e);
        }
    }
    if (useCache) {
        cache.put(content, nextValue);
    }
}

From source file:org.easycloud.las.agent.LogClearThread.java

private boolean shouldDelete(String rootPath, DateFormat df, Date lastPushedTime, File logDir) {
    String absDirPath = logDir.getAbsolutePath();
    String relDirPath = StringUtils.remove(absDirPath, rootPath);
    // TODO hard code "/" here, maybe the windows can't be supported
    if (StringUtils.startsWith(relDirPath, "/")) {
        relDirPath = relDirPath.substring(1);
    }/*from w  w w  .  jav a 2 s  . com*/
    if (StringUtils.endsWith(relDirPath, "/")) {
        relDirPath = relDirPath.substring(0, relDirPath.length() - 1);
    }
    Date loggingTime = parseDate(relDirPath, df);
    if (loggingTime == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("LogPushThread: Parsing the log directory [" + logDir.getPath()
                    + "] failed, and it's skipped.");
        }
        return false;
    } else {
        return TimeUtil.isBeforeNow(loggingTime,
                agentConfiguration.getInt(LOG_CLEAR_BEFORE, DEFAULT_BEFORE_DAYS), Calendar.DATE)
                && TimeUtil.isBefore(loggingTime, lastPushedTime);
    }
}

From source file:org.easycloud.las.agent.LogPushThread.java

private String parseLoggingTime(String rootPath, String postfix, File logFile) {
    String absLogPath = logFile.getAbsolutePath();
    String relLogPath = StringUtils.remove(absLogPath, rootPath);
    if (StringUtils.startsWith(relLogPath, "/")) {
        relLogPath = relLogPath.substring(1);
    }/*from  www.j a v a 2 s  .co  m*/
    return StringUtils.remove(relLogPath, postfix);
}

From source file:org.eclipse.gyrex.cloud.internal.console.ListNodesCmd.java

@Override
protected void doExecute() throws Exception {
    final ICloudManager cloudManager = CloudActivator.getInstance().getService(ICloudManager.class);

    // collect all nodes
    final Collection<String> onlineNodes = cloudManager.getOnlineNodes();
    final Map<String, INodeDescriptor> nodes = new HashMap<String, INodeDescriptor>();
    collectedNodes(nodes, cloudManager.getApprovedNodes());
    collectedNodes(nodes, cloudManager.getPendingNodes());

    // build result list
    final Collection<INodeDescriptor> result = new TreeSet<INodeDescriptor>(new Comparator<INodeDescriptor>() {
        @Override/*from ww w .ja va  2 s .  c  om*/
        public int compare(final INodeDescriptor o1, final INodeDescriptor o2) {
            return o1.getId().compareTo(o2.getId());
        }
    });

    if (StringUtils.isBlank(what)) {
        result.addAll(nodes.values());
    } else if (StringUtils.startsWithIgnoreCase(APPROVED, what)) {
        for (final INodeDescriptor node : nodes.values()) {
            if (node.isApproved()) {
                result.add(node);
            }
        }
    } else if (StringUtils.startsWithIgnoreCase(PENDING, what)) {
        for (final INodeDescriptor node : nodes.values()) {
            if (!node.isApproved()) {
                result.add(node);
            }
        }
    } else if (StringUtils.startsWith(ONLINE, what)) {
        for (final String onlineNode : onlineNodes) {
            final INodeDescriptor node = nodes.get(onlineNode);
            if (null != node) {
                result.add(node);
            }
        }
    }

    for (final INodeDescriptor node : result) {
        if (matchesFilter(filter, node)) {
            final String name = StringUtils.isNotBlank(node.getName()) ? node.getName() : "<unnamed>";
            final String location = StringUtils.isNotBlank(node.getLocation()) ? node.getLocation()
                    : "<unknown>";
            final String tags = StringUtils.join(node.getTags(), ", ");
            final String approved = node.isApproved() ? "approved" : "not approved";
            if (onlineNodes.contains(node.getId())) {
                printf("%s - %s @ %s [%s, online] %s", node.getId(), name, location, approved, tags);
            } else {
                printf("%s - %s @ %s [%s] %s", node.getId(), name, location, approved, tags);
            }
        }
    }
}

From source file:org.eclipse.gyrex.cloud.internal.queue.ZooKeeperQueue.java

/**
 * Returns a sorted map of the queue node children.
 * /*w  w w. ja va  2s  . c om*/
 * @param monitor
 *            optional watcher
 * @return map with key sequence number and value child name
 * @throws KeeperException
 * @throws IllegalStateException
 */
private TreeMap<Long, String> readQueueChildren(final ZooKeeperMonitor monitor)
        throws InterruptedException, IllegalStateException, KeeperException {
    final TreeMap<Long, String> childrenBySequenceNumber = new TreeMap<Long, String>();

    final Collection<String> childNames = ZooKeeperGate.get().readChildrenNames(queuePath, monitor, null);

    for (final String childName : childNames) {
        if (!StringUtils.startsWith(childName, PREFIX)) {
            LOG.warn("Incorrect child name {} in queue {}.", new Object[] { childName, id });
            continue;
        }
        final long sequenceNumber = NumberUtils.toLong(StringUtils.substring(childName, PREFIX.length()), -1);
        if (sequenceNumber < 0) {
            LOG.warn("Incorrect sequence number in child name {} in queue {}.", new Object[] { childName, id });
            continue;
        }
        childrenBySequenceNumber.put(sequenceNumber, childName);
    }

    return childrenBySequenceNumber;
}

From source file:org.eclipse.gyrex.common.console.CommandUtil.java

static void appendCommandDescription(final StrBuilder help, final String name, final Command command,
        final String ident) {
    help.append(ident).append(name);/*from w w w.j ava2  s .c o m*/
    final String description = command.getDescription();
    if (!StringUtils.contains(description, " - ")) {
        help.append(" - ");
    } else if (!StringUtils.startsWith(description, " ")) {
        help.append(' ');
    }
    help.appendln(description);
}