Example usage for java.lang String replaceFirst

List of usage examples for java.lang String replaceFirst

Introduction

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

Prototype

public String replaceFirst(String regex, String replacement) 

Source Link

Document

Replaces the first substring of this string that matches the given regular expression with the given replacement.

Usage

From source file:com.codenvy.ide.git.VFSPermissionsFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    int tokenPlace;
    String lastTokenBeforePath = "/" + gitServerUriPrefix + "/";
    if ((tokenPlace = req.getRequestURL().indexOf(lastTokenBeforePath)) != -1) {
        //get path to project
        String url = req.getRequestURL().substring(tokenPlace + lastTokenBeforePath.length());
        url = url.replaceFirst("/info/refs", "");
        url = url.replaceFirst("/git-upload-pack", "");
        //adaptation to fs
        url = url.replaceAll("/", Matcher.quoteReplacement(File.separator));
        //search for dotVFS directory
        File projectDirectory = Paths.get(vfsRoot, url).toFile();
        String auth;/* w  w w.j  av a2  s  .c o m*/
        String userName = "";
        String password = "";
        if ((auth = req.getHeader("authorization")) != null) {
            //get encoded password phrase
            String userAndPasswordEncoded = auth.substring(6);
            // decode Base64 user:password
            String userAndPasswordDecoded = new String(Base64.decodeBase64(userAndPasswordEncoded));
            //get username and password separator ':'
            int betweenUserAndPassword = userAndPasswordDecoded.indexOf(':');
            //get username - it is before first ':'
            userName = userAndPasswordDecoded.substring(0, betweenUserAndPassword);
            //get password - it is after first ':'
            password = userAndPasswordDecoded.substring(betweenUserAndPassword + 1);
        }

        // Check if user authenticated and has permissions to project, or send response code 403
        boolean needLogout = false;
        String token = null;
        User user;
        try {
            if (!userName.isEmpty()) {
                if (password.equals("x-che")) { // internal SSO
                    token = userName;
                } else {
                    token = getToken(userName, password);
                    if (token == null) {
                        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                        return;
                    }
                    needLogout = true;
                }
                user = getUserBySSO(token);
                EnvironmentContext.getCurrent().setUser(user);
            }

            if (!hasAccessToItem(projectDirectory.getParentFile().getName(), projectDirectory.getName())) {
                if (!userName.isEmpty()) {
                    // Authenticated but no access
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else {
                    // Not authenticated, try again with credentials
                    ((HttpServletResponse) response).addHeader("Cache-Control", "private");
                    ((HttpServletResponse) response).addHeader("WWW-Authenticate", "Basic");
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return;
                }
            }
        } finally {
            if (needLogout) {
                logout();
            }
            EnvironmentContext.reset();
        }
    }
    chain.doFilter(req, response);
}

From source file:com.liferay.portal.google.GoogleConnectImpl.java

public String getProfileImageURL(PortletRequest portletRequest) {
    HttpServletRequest request = PortalUtil.getHttpServletRequest(portletRequest);

    request = PortalUtil.getOriginalServletRequest(request);

    HttpSession session = request.getSession();

    String googleId = (String) session.getAttribute(GoogleWebKeys.GOOGLE_USER_ID);

    if (Validator.isNull(googleId)) {
        return null;
    }//  w ww  .  jav  a  2s.  c o m

    long companyId = PortalUtil.getCompanyId(request);

    String token = (String) session.getAttribute(GoogleWebKeys.GOOGLE_ACCESS_TOKEN);

    JSONObject jsonObject = getGraphResources(companyId, "", token, "");
    String pictureUrl = jsonObject.getString("picture");
    if (pictureUrl == null) {
        return null;
    }

    return pictureUrl.replaceFirst("https:https:", "https:").replaceFirst("http:http:", "http:");
}

From source file:de.fhg.iais.cortex.services.AbstractAipIngestService.java

private String sanitizeOldAscFormat(String inputString) throws JDOMException, IOException {
    if (!StringUtils.containsIgnoreCase(inputString, GlobalConstants.CORTEX_NAMESPACE_URI)) {
        inputString = inputString.replaceFirst("<cortex>",
                "<cortex xmlns=\"" + GlobalConstants.CORTEX_NAMESPACE_URI + "\">");
    }//  w w w.  ja  v  a 2 s  .  c  o m

    StringReader reader = null;
    try {
        reader = new StringReader(inputString);
        Document jdomAip = new SAXBuilder().build(reader);

        XMLOutputter outp = new XMLOutputter();
        outp.setFormat(Format.getPrettyFormat().setEncoding(Charsets.UTF_8.name()));

        if (jdomAip.getRootElement().getChild("edm", GlobalConstants.CORTEX_NAMESPACE) == null) {

            Element child = jdomAip.getRootElement()
                    .getChild("provider-metadata-sets", GlobalConstants.CORTEX_NAMESPACE)
                    .getChild("original-source", GlobalConstants.CORTEX_NAMESPACE);

            if (child.getChildren().size() > 0) {
                String originalSourceCData = outp.outputString((Element) child.getChildren().get(0));
                child.removeContent();
                child.addContent(new CDATA(originalSourceCData));
            }

        }
        return outp.outputString(jdomAip);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:net.portalblockz.portalbot.FeatureListener.java

private String getID(String str) {
    for (String s : str.split(" ")) {
        String regex = "(https?:\\/\\/)?(www.)?youtu\\.be\\/";
        Pattern pat = Pattern.compile(regex);
        Matcher m = pat.matcher(s);
        if (m.find()) {
            return str.replaceFirst(m.group(), "");
        }//from w ww  . j  av a2 s .c o  m
    }
    String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
    Pattern compiledPattern = Pattern.compile(pattern);
    Matcher matcher = compiledPattern.matcher(str);
    if (matcher.find()) {
        return matcher.group();
    }
    return null;
}

From source file:org.dd4t.springmvc.controller.DynamicPageController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    long start = System.currentTimeMillis();

    String URL = request.getRequestURI();

    if (logger.isDebugEnabled())
        logger.debug("Received request in MAV " + URL);

    URL = URL.replaceFirst(request.getContextPath(), "");

    if (logger.isDebugEnabled())
        logger.debug("Request shortened to " + URL);

    GenericPage pageModel = (GenericPage) genericPageFactory.findPageByUrl(URL, publication,
            new BasicRequestContext(request));

    request.setAttribute(Constants.PAGE_MODEL_KEY, pageModel);

    long pagemodeldone = System.currentTimeMillis();

    if (logger.isDebugEnabled())
        logger.debug("Built pageModel for page: " + pageModel.getTitle() + " in " + (pagemodeldone - start)
                + " milliseconds.");

    ComponentViews contentModel = contentController.buildComponentViews(pageModel, request, response);

    long contentmodeldone = System.currentTimeMillis();

    request.setAttribute(Constants.CONTENT_MODEL_KEY, contentModel);

    if (logger.isDebugEnabled())
        logger.debug("Built contentModel: " + contentModel + " in " + (contentmodeldone - pagemodeldone)
                + " milliseconds.");

    /*//ww w .j a v a2 s.c  o m
    Page navigationModel = getNavigationModel(pageModel);
            
    long navmodeldone = System.currentTimeMillis();
            
    if(logger.isDebugEnabled()){
    logger.debug("Built navigationmodel: " + navigationModel+" in "+(navmodeldone-contentmodeldone)+" milliseconds.");
    }  
    request.setAttribute(Constants.NAVIGATION_MODEL_KEY, navigationModel);  
      */

    // attain view
    String view = getViewFromTemplate(pageModel.getPageTemplate());

    // render page through the viewhandler
    String rendered_page = pageViewHandler.handleView(pageModel, pageModel, view, request, response);

    // and write to the response (!)
    response.getWriter().write(rendered_page);

    if (logger.isInfoEnabled()) {
        long end = System.currentTimeMillis();
        logger.info("Built pageresponse in " + (end - start) + " milliseconds.");
    }

    return null;
}

From source file:org.openmrs.module.sdmxhdintegration.web.controller.MapDimensionDialogController.java

/**
 * Handles submission of dimension mapping dialog
 *///from   w w w  .j  a  va 2 s  .  c o m
@RequestMapping(method = RequestMethod.POST)
public String handleDialogSubmit(WebRequest request,
        @RequestParam("mappedOMRSDimensionId") Integer mappedOMRSDimensionId,
        @RequestParam("messageId") Integer messageId, @RequestParam("sdmxhdDimension") String sdmxhdDimension,
        @RequestParam("keyFamilyId") String keyFamilyId,
        @RequestParam(value = "fixedValueCheckbox", required = false) String fixedValueCheckbox,
        @RequestParam(value = "fixedValue", required = false) String fixedValue) throws Exception {
    sdmxhdDimension = URLDecoder.decode(sdmxhdDimension);

    SDMXHDMessage message = Context.getService(SDMXHDService.class).getMessage(messageId);
    SDMXHDCohortIndicatorDataSetDefinition omrsDSD = Utils.getDataSetDefinition(message, keyFamilyId);

    // delete previous mappings if there are any
    Integer omrsDimensionId = omrsDSD.getOMRSMappedDimension(sdmxhdDimension);
    if (omrsDimensionId != null) {
        // remove previous dimensions
        omrsDSD.removeDimension(omrsDimensionId + "");
        // TODO remove all Columns that use that dimension (reporting ticket?)
    }
    omrsDSD.getOMRSMappedDimensions().remove(sdmxhdDimension);
    omrsDSD.getOMRSMappedDimensionOptions().remove(sdmxhdDimension);
    omrsDSD.getFixedDimensionValues().remove(sdmxhdDimension);

    if (fixedValueCheckbox != null) {
        omrsDSD.addFixedDimensionValues(sdmxhdDimension, fixedValue);
    } else {
        // Build up Dimension Options Map
        Map<String, String> mappedDimOpts = new HashMap<String, String>();
        Map<String, String[]> paramMap = request.getParameterMap();
        for (String key : paramMap.keySet()) {
            if (key.startsWith(DIM_OPT)) {
                String mappedSDMXHSDimension = key.replaceFirst(DIM_OPT, "");
                String mappedOMRSDimension = paramMap.get(key)[0];
                mappedDimOpts.put(mappedSDMXHSDimension, mappedOMRSDimension);
            }
        }

        // Map Dimension and Dimension options
        omrsDSD.mapDimension(sdmxhdDimension, mappedOMRSDimensionId, mappedDimOpts);

        // add dimension to DataSet
        DimensionService ds = Context.getService(DimensionService.class);
        CohortDefinitionDimension omrsDimension = ds.getDefinition(CohortDefinitionDimension.class,
                mappedOMRSDimensionId);
        omrsDimension.addParameters(IndicatorUtil.getDefaultParameters());
        omrsDimension = (CohortDefinitionDimension) ds.saveDefinition(omrsDimension);
        omrsDSD.addDimension(mappedOMRSDimensionId + "", omrsDimension,
                IndicatorUtil.getDefaultParameterMappings());
    }

    // save dataset
    DataSetDefinitionService dss = Context.getService(DataSetDefinitionService.class);
    dss.saveDefinition(omrsDSD);

    return "redirect:redirectParent.form?url=keyFamilyMapping.form?messageId=" + messageId + "%26keyFamilyId="
            + keyFamilyId;
}

From source file:org.kaaproject.kaa.server.common.admin.KaaRestTemplate.java

private URI updateUrl(URI url) {
    String currentUri = url.toString();

    int sufixPartIdx = currentUri.indexOf(restApiSuffix);

    String defaultUriPartWithVariableHostPort = currentUri.substring(0, sufixPartIdx);
    String sufixPart = currentUri.substring(sufixPartIdx);

    defaultUriPartWithVariableHostPort = defaultUriPartWithVariableHostPort.replaceFirst(url.getHost(),
            getCurHost());/* ww  w  .java 2 s  .  co  m*/
    defaultUriPartWithVariableHostPort = defaultUriPartWithVariableHostPort
            .replaceFirst(String.valueOf(url.getPort()), String.valueOf(getCurPort()));

    return URI.create(defaultUriPartWithVariableHostPort + sufixPart);
}

From source file:hjow.hgtable.util.DataUtil.java

/**
 * <p> ??  ?   ??  . finds   ? -1 ? .</p>
 * //  ww w . j  av  a 2  s .c  o m
 * @param text : ?
 * @param finds : 
 * @return  ? 
 */
public static int has(String text, String finds) {
    int results = 0;
    String target = text;

    if (finds.equals(""))
        return -1;

    while (text.indexOf(finds) >= 0) {
        results = results + 1;
        target = target.replaceFirst(finds, "");
    }

    return results;
}

From source file:net.hillsdon.reviki.webtests.WebTestSupport.java

protected String removeSessionId(final String url) {
    // The first caters for Tomcat, the second Jetty.
    return url.replaceFirst("[;][^?]*", "").replaceFirst("%3B[^?]*", "");
}