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

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

Introduction

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

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

private String getPartialUrl(String fullUrl) {
    if (StringUtils.startsWith(fullUrl, "http")) {
        int idx = StringUtils.indexOf(fullUrl, "/", 7);
        return idx == -1 ? "/" : StringUtils.substring(fullUrl, idx);
    }/*  ww  w.  j a v a 2  s  .c  o  m*/

    return fullUrl;
}

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

/**
 * Support data structures where link metadata is stored in mutliple HTML5 data-* attributes.
 * @param pResourceProps Valuemap to write link metadata to
 * @param element Link element/*from  ww  w  .j a va 2  s.c o  m*/
 * @return true if any metadata attribute was found
 */
private boolean getAnchorMetadataFromData(ValueMap pResourceProps, Element element) {
    boolean foundAny = false;

    List<Attribute> attributes = element.getAttributes();
    for (Attribute attribute : attributes) {
        if (DataPropertyUtil.isHtml5DataName(attribute.getName())) {
            String value = attribute.getValue();
            if (StringUtils.isNotEmpty(value)) {
                String property = DataPropertyUtil.toHeadlessCamelCaseName(attribute.getName());
                if (StringUtils.startsWith(value, "[") && StringUtils.endsWith(value, "]")) {
                    try {
                        JSONArray jsonArray = new JSONArray(value);
                        String[] values = new String[jsonArray.length()];
                        for (int i = 0; i < jsonArray.length(); i++) {
                            values[i] = jsonArray.optString(i);
                        }
                        pResourceProps.put(property, values);
                    } catch (JSONException ex) {
                        // ignore
                    }
                } else {
                    // decode if required
                    value = decodeIfEncoded(value);
                    pResourceProps.put(property, value);
                }
                foundAny = true;
            }
        }
    }

    return foundAny;
}

From source file:com.bekwam.resignator.commands.UnsignCommand.java

private void removeSigs(File metaInfDir) {
    File[] sfFiles = metaInfDir.listFiles(pathname -> StringUtils.endsWith(pathname.getName(), ".SF"));
    for (File sf : sfFiles) {
        File[] dsfFiles = metaInfDir.listFiles(
                pathname -> StringUtils.startsWith(pathname.getName(), FilenameUtils.getBaseName(sf.getName()))
                        && !StringUtils.endsWith(pathname.getName(), ".SF"));
        for (File dsf : dsfFiles) {
            if (logger.isDebugEnabled()) {
                logger.debug("[UNSIGN] deleting dsf={}", dsf.getName());
            }//from ww  w .  jav  a2 s.  c  o m
            dsf.delete();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("[UNSIGN] deleting sf={}", sf.getName());
        }
        sf.delete();
    }
}

From source file:alfio.manager.UploadedResourceManager.java

private static Map<String, String> getAttributes(UploadBase64FileModification file) {
    if (!StringUtils.startsWith(file.getType(), "image/")) {
        return file.getAttributes();
    }//from  ww w  .  j a  va 2  s  .c  o m

    try {
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getFile()));
        Map<String, String> attributes = new HashMap<>(file.getAttributes());
        attributes.put(ATTR_IMG_WIDTH, String.valueOf(image.getWidth()));
        attributes.put(ATTR_IMG_HEIGHT, String.valueOf(image.getHeight()));
        return attributes;
    } catch (IOException e) {
        log.error("error while processing image: ", e);
        return file.getAttributes();
    }
}

From source file:com.thoughtworks.go.domain.ArtifactPlan.java

protected String destinationURL(File rootPath, File file, String src, String dest) {
    String trimmedPattern = rtrimStandardrizedWildcardTokens(src);
    if (StringUtils.equals(FilenameUtils.separatorsToUnix(trimmedPattern),
            FilenameUtils.separatorsToUnix(src))) {
        return dest;
    }/*from  www  . j ava 2 s  . c o m*/
    String trimmedPath = removeStart(subtractPath(rootPath, file),
            FilenameUtils.separatorsToUnix(trimmedPattern));
    if (!StringUtils.startsWith(trimmedPath, "/") && StringUtils.isNotEmpty(trimmedPath)) {
        trimmedPath = "/" + trimmedPath;
    }
    return dest + trimmedPath;
}

From source file:com.erudika.para.client.ParaClient.java

private String getFullPath(String resourcePath) {
    if (StringUtils.startsWith(resourcePath, JWT_PATH)) {
        return resourcePath;
    }//  ww  w  .j a  v a2s.c  o  m
    if (resourcePath == null) {
        resourcePath = "";
    } else if (resourcePath.startsWith("/")) {
        resourcePath = resourcePath.substring(1);
    }
    return getApiPath() + resourcePath;
}

From source file:de.micromata.genome.jpa.EmgrFactory.java

/**
 * Convert exception./*from ww  w. ja v  a  2  s  . c om*/
 *
 * @param ex the ex
 * @return the runtime exception
 */
public static RuntimeException convertException(RuntimeException ex) {
    if (ex instanceof QueryTimeoutException) {
        // this is a oracle/hibernate bug workouround.
        // hibernate think this is is a query timeout, but should a DataException
        if (ex.getCause() instanceof org.hibernate.QueryTimeoutException) {
            org.hibernate.QueryTimeoutException qto = (org.hibernate.QueryTimeoutException) ex.getCause();
            if (qto.getCause() instanceof SQLException) {
                SQLException sqlex = (SQLException) qto.getCause();
                // ORA-12899
                if (sqlex.getErrorCode() == 12899) {
                    return new DataPersistenceException(ex.getMessage(), qto.getSQL(), sqlex.getSQLState(), ex);
                }
            }
        }
    }
    if (ex instanceof PersistenceException) {
        Throwable cause = ex.getCause();
        if (cause instanceof ConstraintViolationException) {
            ConstraintViolationException cve = (ConstraintViolationException) cause;
            cve.getMessage();
            String sql = cve.getSQL();
            return new ConstraintPersistenceException(cve.getMessage(), sql, cve.getSQLState(),
                    cve.getConstraintName(), ex);
        } else if (cause instanceof DataException) {
            DataException dex = (DataException) cause;
            return new DataPersistenceException(ex.getMessage(), dex.getSQL(), dex.getSQLState(), ex);
        } else if (cause instanceof PropertyValueException) {
            if (StringUtils.startsWith(cause.getMessage(), "not-null ") == true) {
                return new NullableConstraintPersistenceException(ex.getMessage(), ex);
            }
        }
    }
    return ex;
}

From source file:alfio.config.MvcConfiguration.java

@Bean
public HandlerInterceptorAdapter getDefaultTemplateObjectsFiller() {
    return new HandlerInterceptorAdapter() {
        @Override// w w  w  .j  a v a2s  .c  o m
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
            Optional.ofNullable(modelAndView)
                    .filter(mv -> !StringUtils.startsWith(mv.getViewName(), "redirect:")).ifPresent(mv -> {
                        mv.addObject("request", request);
                        final ModelMap modelMap = mv.getModelMap();

                        boolean demoModeEnabled = environment.acceptsProfiles(Initializer.PROFILE_DEMO);

                        modelMap.put("demoModeEnabled", demoModeEnabled);

                        Optional.ofNullable(request.getAttribute("ALFIO_EVENT_NAME")).map(Object::toString)
                                .ifPresent(eventName -> {

                                    List<?> availableLanguages = i18nManager.getEventLanguages(eventName);

                                    modelMap.put("showAvailableLanguagesInPageTop",
                                            availableLanguages.size() > 1);
                                    modelMap.put("availableLanguages", availableLanguages);
                                });

                        modelMap.putIfAbsent("event", null);
                        modelMap.putIfAbsent("pageTitle", "empty");
                        Event event = modelMap.get("event") == null ? null
                                : modelMap.get("event") instanceof Event ? (Event) modelMap.get("event")
                                        : ((EventDescriptor) modelMap.get("event")).getEvent();
                        ConfigurationPathKey googleAnalyticsKey = Optional.ofNullable(event)
                                .map(e -> alfio.model.system.Configuration.from(e.getOrganizationId(),
                                        e.getId(), GOOGLE_ANALYTICS_KEY))
                                .orElseGet(() -> alfio.model.system.Configuration
                                        .getSystemConfiguration(GOOGLE_ANALYTICS_KEY));
                        modelMap.putIfAbsent("analyticsEnabled", StringUtils
                                .isNotBlank(configurationManager.getStringConfigValue(googleAnalyticsKey, "")));

                        if (demoModeEnabled) {
                            modelMap.putIfAbsent("paypalTestUsername",
                                    configurationManager.getStringConfigValue(alfio.model.system.Configuration
                                            .getSystemConfiguration(PAYPAL_DEMO_MODE_USERNAME), "<missing>"));
                            modelMap.putIfAbsent("paypalTestPassword",
                                    configurationManager.getStringConfigValue(alfio.model.system.Configuration
                                            .getSystemConfiguration(PAYPAL_DEMO_MODE_PASSWORD), "<missing>"));
                        }
                    });
        }
    };
}

From source file:com.nridge.connector.common.con_com.crawl.CrawlStart.java

/**
 * Parses a file identified by the path/file name parameter
 * and loads it into an internally managed crawler start URI
 * list.// www . jav  a 2 s .c o  m
 *
 * @param aPathFileName Absolute file name (e.g. 'crawl_start.txt').
 *
 * @throws IOException I/O related exception.
 */
public void load(String aPathFileName) throws IOException {
    List<String> lineList;
    Logger appLogger = mAppMgr.getLogger(this, "load");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    try (FileReader fileReader = new FileReader(aPathFileName)) {
        lineList = IOUtils.readLines(fileReader);
    }

    for (String followString : lineList) {
        if (!StringUtils.startsWith(followString, "#"))
            mStartList.add(followString);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.connector.fs.con_fs.restlet.ResourceDocView.java

/**
 * Returns a full representation containing the document response message
 * to the Restlet framework./*from   w  w  w .  j  a v  a  2 s . co m*/
 *
 * @return A Representation - the content of a representation can be retrieved
 * several times if there is a stable and accessible source, like a local file
 * or a string.
 *
 * @throws org.restlet.resource.ResourceException Encapsulates a response status and the optional
 * cause as a checked exception.
 */
@Override
protected Representation get() throws ResourceException {
    String msgStr;
    Representation replyRepresentation;
    RestletApplication restletApplication = (RestletApplication) getApplication();
    AppMgr appMgr = restletApplication.getAppMgr();

    Logger appLogger = appMgr.getLogger(this, "get");

    appLogger.trace(appMgr.LOGMSG_TRACE_ENTER);

    Reference originalReference = getOriginalRef();
    Form queryForm = originalReference.getQueryAsForm();
    String docId = queryForm.getFirstValue("id");

    if (StringUtils.isNotEmpty(docId)) {
        DataBag docBag = loadDocument(docId);
        if (docBag.count() == 0) {
            msgStr = (String) docBag.getProperty(PROPERTY_ERROR_MESSAGE);
            replyRepresentation = messageRepresentation(msgStr);
        } else {
            String nsdURL = docBag.getValueAsString("nsd_url");
            if (StringUtils.startsWith(nsdURL, "file:")) {
                String mimeType = docBag.getValueAsString("nsd_mime_type");
                if (StringUtils.isEmpty(mimeType))
                    mimeType = "application/octet-stream";
                try {
                    URI uriFile = new URI(nsdURL);
                    File viewFile = new File(uriFile);
                    replyRepresentation = new FileRepresentation(viewFile, MediaType.valueOf(mimeType));
                } catch (URISyntaxException e) {
                    msgStr = String.format("%s: %s", nsdURL, e.getMessage());
                    appLogger.error(msgStr, e);
                    msgStr = String.format("Cannot view document - invalid URI for document id '%s'.", docId);
                    replyRepresentation = messageRepresentation(msgStr);
                }
            } else {
                msgStr = String.format("Cannot view document - invalid URI for document id '%s'.", docId);
                replyRepresentation = messageRepresentation(msgStr);
            }
        }
    } else
        replyRepresentation = messageRepresentation("Cannot view document - missing id in request.");

    appLogger.trace(appMgr.LOGMSG_TRACE_DEPART);

    return replyRepresentation;
}