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.glaf.report.runtime.ReportContainer.java

public Map<String, ReportDefinition> reload() {
    Map<String, ReportDefinition> reportMap = new java.util.HashMap<String, ReportDefinition>();
    String configLocation = SystemProperties.getString("report.config.path");
    if (StringUtils.isEmpty(configLocation)) {
        configLocation = CustomProperties.getString("report.config.path");
    }/*from   ww  w .j av  a2s  . c  o  m*/
    if (StringUtils.isEmpty(configLocation)) {
        configLocation = DEFAULT_CONFIG_PATH;
    }

    ReportDefinitionReader reader = new ReportDefinitionReader();
    InputStream inputStream = null;
    try {
        String configPath = SystemProperties.getConfigRootPath() + configLocation;
        logger.info(configPath);
        File directory = new File(configPath);
        if (directory.isDirectory()) {
            String[] filelist = directory.list();
            if (filelist != null) {
                for (int i = 0, len = filelist.length; i < len; i++) {
                    String filename = configPath + sp + filelist[i];
                    File file = new File(filename);
                    if (file.isFile() && file.getName().endsWith(".report.xml")) {
                        logger.debug(file.getAbsolutePath());
                        inputStream = new FileInputStream(file);
                        List<ReportDefinition> reports = reader.read(inputStream);
                        for (ReportDefinition rdf : reports) {
                            reportMap.put(rdf.getReportId(), rdf);
                        }
                        inputStream.close();
                        inputStream = null;
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
    }

    try {
        IReportService reportService = ContextFactory.getBean("reportService");
        ReportQuery query = new ReportQuery();
        query.enableFlag("1");
        List<Report> reports = reportService.list(query);
        if (reports != null && !reports.isEmpty()) {
            for (Report rpt : reports) {
                if (StringUtils.isNotEmpty(rpt.getReportTemplate())) {
                    String filename = rpt.getReportTemplate();
                    if (StringUtils.startsWith(rpt.getReportTemplate(), "/WEB-INF")) {
                        filename = SystemProperties.getAppPath() + rpt.getReportTemplate();
                    }
                    File file = new File(filename);
                    if (file.exists() && file.isFile()) {
                        logger.debug(file.getAbsolutePath());
                        byte[] bytes = FileUtils.getBytes(file);
                        ReportDefinition rd = new ReportDefinition();
                        rd.setData(bytes);
                        rd.setReportId(rpt.getId());
                        rd.setTemplateFile(rpt.getReportTemplate());
                        reportMap.put(rd.getReportId(), rd);

                        ReportDefinition rd2 = new ReportDefinition();
                        rd2.setData(bytes);
                        rd2.setReportId(rpt.getName());
                        rd2.setTemplateFile(rpt.getReportTemplate());
                        reportMap.put(rd2.getReportId(), rd2);
                    }
                }
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
    return reportMap;
}

From source file:io.wcm.maven.plugins.nodejs.installation.NodeInstallationInformation.java

private static String getWindowsNpmVersion(String npmVersion) {
    if (StringUtils.startsWith(npmVersion, "2.")) {
        return LATEST_WINDOWS_NPM_VERSION;
    }/* w  w w .  j a  v a2s . co m*/
    return npmVersion;
}

From source file:com.nridge.connector.common.con_com.publish.PSolr.java

/**
 * Returns a typed value for the property name identified
 * or the default value (if unmatched)./*  w  w  w. ja  v  a  2  s  .c om*/
 *
 * @param aSuffix Property name suffix.
 * @param aDefaultValue Default value to return if property
 *                      name is not matched.
 *
 * @return Value of the property.
 */
private int getCfgInteger(String aSuffix, int aDefaultValue) {
    String propertyName;

    if (StringUtils.startsWith(aSuffix, "."))
        propertyName = mCfgPropertyPrefix + aSuffix;
    else
        propertyName = mCfgPropertyPrefix + "." + aSuffix;

    return mAppMgr.getInt(propertyName, aDefaultValue);
}

From source file:io.wcm.devops.conga.generator.plugins.fileheader.AbstractFileHeader.java

/**
 * Extract file header from the beginning of file with all lines starting with line prefix.
 * @param file File File/*  w w  w  .j  av a2s. co  m*/
 * @return File header or null
 */
protected final FileHeaderContext extractFileHeaderWithLinePrefixes(FileContext file) {
    try {
        if (StringUtils.isNotEmpty(getLineBreak()) && StringUtils.isNotEmpty(getCommentLinePrefix())) {
            String content = FileUtils.readFileToString(file.getFile(), file.getCharset());
            int insertPosition = getInsertPosition(content);
            content = content.substring(insertPosition);

            String[] contentLines = StringUtils.split(content, getLineBreak());
            if (contentLines.length > 0 && StringUtils.startsWith(contentLines[0], getCommentLinePrefix())) {
                List<String> lines = new ArrayList<>();
                for (int i = 0; i < contentLines.length; i++) {
                    if (StringUtils.startsWith(contentLines[i], getCommentLinePrefix())) {
                        lines.add(contentLines[i].substring(getCommentLinePrefix().length()));
                    } else {
                        break;
                    }
                }
                if (!lines.isEmpty()) {
                    return new FileHeaderContext().commentLines(lines);
                }
            }
        }
    } catch (IOException ex) {
        throw new GeneratorException("Unable parse add file header from " + FileUtil.getCanonicalPath(file),
                ex);
    }
    return null;
}

From source file:de.micromata.genome.gwiki.jetty.GWikiJettyStarter.java

public void start(JettyStartListener listener) {
    try {//  www  . j  a  v  a  2  s  . c om
        LocalSettings localSettings = LocalSettings.get();
        Log4JInitializer.initializeLog4J();
        localSettings.logloadedFiles();

        LocalSettingsEnv localSettingsEnv = LocalSettingsEnv.get();
        String contextFile = localSettings.get("gwiki.contextfile", "res:/StandaloneGWikiContext.xml");
        GWikiBootstrapConfigLoader cfgLoader;
        if (StringUtils.startsWith(contextFile, "res:") == true) {
            String fileName = contextFile.substring("res:".length());
            GWikiCpContextBootstrapConfigLoader cploader = new GWikiCpContextBootstrapConfigLoader();
            cploader.setFileName(fileName);
            cfgLoader = cploader;
        } else {
            GwikiFileContextBootstrapConfigLoader fcfgLoader = new GwikiFileContextBootstrapConfigLoader();
            if (StringUtils.isNotBlank(contextFile) == true) {
                fcfgLoader.setFileName(contextFile);
            } else {
                contextFile = ".";
            }
            cfgLoader = fcfgLoader;
        }
        wikibootcfg = cfgLoader.loadConfig(null);
        jettyConfig = (JettyConfig) cfgLoader.getBeanFactory().getBean("JettyConfig");
        server = new Server(jettyConfig.getPort());

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.getInitParams().putAll(localSettings.getMap());

        // upload applet needs this. set limit to 100mb
        context.setMaxFormContentSize(1024 * 1024 * 100);
        if (jettyConfig.getContextPath() == null || jettyConfig.getContextPath().equals("/") == true) {
            jettyConfig.setContextPath("");
        }
        context.setContextPath(jettyConfig.getContextPath());
        context.setResourceBase(jettyConfig.getContextRoot());
        context.getSessionHandler().getSessionManager().setMaxInactiveInterval(jettyConfig.getSessionTimeout());
        wikiServlet = new GWikiServlet();
        ServletHolder wikiServletHolder = new ServletHolder(wikiServlet);
        wikiServlet.setDAOContext(wikibootcfg);
        context.addServlet(wikiServletHolder, jettyConfig.getServletPath() + "*");
        server.setHandler(context);
        if (jettyConfig.getConnectors() != null) {
            for (Connector con : jettyConfig.getConnectors()) {
                server.addConnector(con);
            }
        }
        configureLogging(server, context);
        // Handler[] handlers = server.getHandlers();
        server.start();

        System.out.println(
                "You can now use gwiki with your web browser: " + LocalSettings.get().get("gwiki.public.url"));
        listener.started(StartSucces.Success, null);
        server.join();
    } catch (RuntimeException ex) {
        listener.started(StartSucces.Error, ex);
        throw ex;
    } catch (Exception ex) {
        listener.started(StartSucces.Error, ex);
        throw new RuntimeException(ex);
    }
}

From source file:io.wcm.maven.plugins.contentpackage.DownloadMojo.java

/**
 * Download content package from CRX instance
 *//*  w w  w  .j a  v  a 2s . co  m*/
private File downloadFile(File file, String ouputFilePath) throws MojoExecutionException {
    try (CloseableHttpClient httpClient = getHttpClient()) {
        getLog().info("Download " + file.getName() + " from " + getCrxPackageManagerUrl());

        // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
        HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload");
        MultipartEntityBuilder entity = MultipartEntityBuilder.create().addBinaryBody("package", file)
                .addTextBody("force", "true");
        post.setEntity(entity.build());
        JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post);
        boolean success = jsonResponse.optBoolean("success", false);
        String msg = jsonResponse.optString("msg", null);
        String path = jsonResponse.optString("path", null);

        // package already exists - get path from error message and continue
        if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX)
                && StringUtils.isEmpty(path)) {
            path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
            success = true;
        }
        if (!success) {
            throw new MojoExecutionException("Package path detection failed: " + msg);
        }

        getLog().info("Package path is: " + path + " - now rebuilding package...");

        // 2nd: build package
        HttpPost buildMethod = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + path + "?cmd=build");
        executePackageManagerMethodHtml(httpClient, buildMethod, 0);

        // 3rd: download package
        String crxUrl = StringUtils.removeEnd(getCrxPackageManagerUrl(), "/crx/packmgr/service");
        HttpGet downloadMethod = new HttpGet(crxUrl + path);

        // execute download
        CloseableHttpResponse response = httpClient.execute(downloadMethod);
        try {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                // get response stream
                InputStream responseStream = response.getEntity().getContent();

                // delete existing file
                File outputFileObject = new File(ouputFilePath);
                if (outputFileObject.exists()) {
                    outputFileObject.delete();
                }

                // write response file
                FileOutputStream fos = new FileOutputStream(outputFileObject);
                IOUtil.copy(responseStream, fos);
                fos.flush();
                responseStream.close();
                fos.close();

                getLog().info("Package downloaded to " + outputFileObject.getAbsolutePath());

                return outputFileObject;
            } else {
                throw new MojoExecutionException(
                        "Package download failed:\n" + EntityUtils.toString(response.getEntity()));
            }
        } finally {
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                try {
                    response.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (FileNotFoundException ex) {
        throw new MojoExecutionException("File not found: " + file.getAbsolutePath(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException("Download operation failed.", ex);
    }
}

From source file:io.wcm.handler.mediasource.dam.DamMediaSource.java

@Override
public void enableMediaDrop(HtmlElement element, MediaRequest mediaRequest) {
    if (wcmMode == WCMMode.DISABLED || wcmMode == null) {
        return;/* w ww.  j  a v a 2  s .c  o  m*/
    }

    String refProperty = getMediaRefProperty(mediaRequest);
    if (!StringUtils.startsWith(refProperty, "./")) {
        refProperty = "./" + refProperty; //NOPMD
    }

    String cropProperty = getMediaCropProperty(mediaRequest);
    if (!StringUtils.startsWith(cropProperty, "./")) {
        cropProperty = "./" + cropProperty; //NOPMD
    }

    String name = refProperty;
    if (StringUtils.contains(name, "/")) {
        name = Text.getName(name);
    }

    if (componentContext != null && componentContext.getEditContext() != null
            && MediaMarkupBuilderUtil.canApplyDragDropSupport(mediaRequest, componentContext)) {
        Component componentDefinition = WCMUtils.getComponent(resource);

        // set drop target - with path of current component as default resource type
        Map<String, String> params = new HashMap<String, String>();
        if (componentDefinition != null) {
            params.put("./" + ResourceResolver.PROPERTY_RESOURCE_TYPE, componentDefinition.getPath());

            // clear cropping parameters if a new image is inserted via drag&drop
            params.put(cropProperty, "");
        }

        DropTarget dropTarget = new DropTargetImpl(name, refProperty).setAccept(new String[] { "image/.*" // allow all image mime types
        }).setGroups(new String[] { "media" // allow drop from DAM contentfinder tab
        }).setParameters(params);

        componentContext.getEditContext().getEditConfig().getDropTargets().put(dropTarget.getId(), dropTarget);

        if (element != null) {
            element.addCssClass(DropTarget.CSS_CLASS_PREFIX + name);
        }
    }
}

From source file:de.knightsoftnet.validators.shared.impl.PhoneNumberValueRestValidator.java

private String urlEncode(final String pphoneNumber) {
    if (StringUtils.startsWith(pphoneNumber, "+")) {
        return "%2B" + URL.encode(StringUtils.substring(pphoneNumber, 1));
    } else {// w w w . j  a  v a2 s .com
        return URL.encode(pphoneNumber);
    }
}

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

public List<KeystoreEntry> parseKeystoreEntries(BufferedReader br) throws IOException {

    List<KeystoreEntry> entries = new ArrayList<>();

    String line = "";
    KeystoreListParseStateType parseState = KeystoreListParseStateType.HEADER;
    KeystoreEntry currEntry = null;//  w  w w.  ja va2s .  co m

    while (parseState != KeystoreListParseStateType.END && parseState != KeystoreListParseStateType.ERROR_END) {

        switch (parseState) {
        case START:
            parseState = KeystoreListParseStateType.HEADER;
            break;
        case HEADER:

            line = br.readLine();

            if (StringUtils.startsWith(line, "Your keystore")) {
                parseState = KeystoreListParseStateType.ENTRY;
            } else if (line == null) {
                parseState = KeystoreListParseStateType.ERROR_END;
            }

            break;
        case ENTRY:

            line = br.readLine();

            if (StringUtils.startsWith(line, "Certificate fingerprint")) {
                parseState = KeystoreListParseStateType.FP;
            } else {

                if (line == null) {

                    parseState = KeystoreListParseStateType.ERROR_END;

                } else if (StringUtils.isNotEmpty(line)) {
                    String[] toks = StringUtils.split(line, ",");
                    currEntry = new KeystoreEntry(StringUtils.trim(toks[0]),
                            StringUtils.trim(toks[1] + toks[2]), StringUtils.trim(toks[3]));
                }
            }

            break;
        case FP:

            if (StringUtils.isNotEmpty(line)) {
                StrTokenizer st = new StrTokenizer(line, ": ");
                if (st != null) {
                    String[] toks = st.getTokenArray();
                    currEntry = new KeystoreEntry(currEntry, toks[1]);
                    entries.add(currEntry);
                }
            }

            parseState = KeystoreListParseStateType.ENTRY;
            break;

        case ERROR_END:
        case END:
            break;
        }
    }

    return entries;
}

From source file:com.adobe.cq.wcm.core.components.internal.servlets.SearchResultServlet.java

private Resource getSearchContentResource(SlingHttpServletRequest request, Page currentPage) {
    Resource searchContentResource = null;
    RequestPathInfo requestPathInfo = request.getRequestPathInfo();
    Resource resource = request.getResource();
    String relativeContentResource = requestPathInfo.getSuffix();
    if (StringUtils.startsWith(relativeContentResource, "/")) {
        relativeContentResource = StringUtils.substring(relativeContentResource, 1);
    }/* w  w  w  .  ja v  a 2 s .  c om*/
    if (StringUtils.isNotEmpty(relativeContentResource)) {
        searchContentResource = resource.getChild(relativeContentResource);
        if (searchContentResource == null) {
            PageManager pageManager = resource.getResourceResolver().adaptTo(PageManager.class);
            if (pageManager != null) {
                Template template = currentPage.getTemplate();
                if (template != null) {
                    Resource templateResource = request.getResourceResolver().getResource(template.getPath());
                    if (templateResource != null) {
                        searchContentResource = templateResource
                                .getChild(NN_STRUCTURE + "/" + relativeContentResource);
                    }
                }
            }
        }
    }
    return searchContentResource;
}