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:org.mashupmedia.service.MapperManagerImpl.java

@Override
public void saveXmltoSongs(MusicLibrary musicLibrary, String xml) throws Exception {

    String libraryPath = StringUtils.trimToEmpty(musicLibrary.getLocation().getPath());
    libraryPath = libraryPath.replaceFirst("/app/.*", "");

    List<Song> songs = new ArrayList<Song>();

    if (StringUtils.isBlank(xml)) {
        logger.error("Unable to save remote songs, xml is empty");
        return;//from   w w  w.  j a v  a2s . c  o m
    }

    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());

    PartialUnmarshaller<Song> partialUnmarshaller = new PartialUnmarshaller<Song>(inputStream, Song.class);

    while (partialUnmarshaller.hasNext()) {
        Song song = partialUnmarshaller.next();
        String title = StringEscapeUtils.unescapeXml(song.getTitle());
        song.setTitle(title);
        Album album = song.getAlbum();
        album.setId(0);

        songs.add(song);

        if (songs.size() == 10) {
            musicLibraryUpdateManager.saveSongs(musicLibrary, songs);
            songs.clear();
        }
    }

    partialUnmarshaller.close();
    musicLibraryUpdateManager.saveSongs(musicLibrary, songs);

}

From source file:io.openvidu.test.e2e.utils.CustomHttpClient.java

public CustomHttpClient(String openviduUrl, String openviduSecret) {
    this.openviduUrl = openviduUrl.replaceFirst("/*$", "");
    this.headerAuth = "Basic "
            + Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + openviduSecret).getBytes());

    SSLContext sslContext = null;
    try {/*  w w  w .ja v a 2 s .  c  o m*/
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        Assert.fail("Error building custom HttpClient: " + e.getMessage());
    }
    HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    Unirest.setHttpClient(unsafeHttpClient);
}

From source file:org.apache.rya.indexing.smarturi.SmartUriAdapter.java

/**
 * Serializes a map into a URI./*from w ww .j  a va 2 s  . c  om*/
 * @param subject the {@link RyaURI} subject of the Entity. Identifies the
 * thing that is being represented as an Entity.
 * @param map the {@link Map} of {@link URI}s to {@link Value}s.
 * @return the Smart {@link URI}.
 * @throws SmartUriException
 */
public static URI serializeUri(final RyaURI subject, final Map<URI, Value> map) throws SmartUriException {
    final String subjectData = subject.getData();
    final int fragmentPosition = subjectData.indexOf("#");
    String prefix = subjectData;
    String fragment = null;
    if (fragmentPosition > -1) {
        prefix = subjectData.substring(0, fragmentPosition);
        fragment = subjectData.substring(fragmentPosition + 1, subjectData.length());
    }

    URIBuilder uriBuilder = null;
    try {
        if (fragmentPosition > -1) {
            uriBuilder = new URIBuilder(new java.net.URI("urn://" + fragment));
        } else {
            uriBuilder = new URIBuilder(new java.net.URI(subjectData.replaceFirst(":", "://")));
        }
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Unable to serialize a Smart URI from the provided properties", e);
    }
    final List<NameValuePair> nameValuePairs = new ArrayList<>();

    for (final Entry<URI, Value> entry : map.entrySet()) {
        final URI key = entry.getKey();
        final Value value = entry.getValue();
        nameValuePairs.add(new BasicNameValuePair(key.getLocalName(), value.stringValue()));
    }

    uriBuilder.setParameters(nameValuePairs);

    URI uri = null;
    try {
        if (fragmentPosition > -1) {
            final java.net.URI partialUri = uriBuilder.build();
            final String uriString = StringUtils.removeStart(partialUri.getRawSchemeSpecificPart(), "//");
            final URIBuilder fragmentUriBuilder = new URIBuilder(new java.net.URI(prefix));
            fragmentUriBuilder.setFragment(uriString);
            final String fragmentUriString = fragmentUriBuilder.build().toString();
            uri = new URIImpl(fragmentUriString);
        } else {
            final String uriString = uriBuilder.build().toString();
            uri = new URIImpl(uriString);
        }
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Smart URI could not serialize the property map.", e);
    }

    return uri;
}

From source file:com.wso2telco.dep.reportingservice.dao.OperatorDAO.java

/**
 * Gets the approved operators by application.
 *
 * @param applicationId the application id
 * @param operator the operator/*from   w  w w .j a v a2  s . co m*/
 * @return the approved operators by application
 */
public static String getApprovedOperatorsByApplication(int applicationId, String operator) {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String sql = "SELECT opco.operatorname FROM " + ReportingTable.OPERATORAPPS + " opcoApp INNER JOIN "
            + ReportingTable.OPERATORS
            + " opco ON opcoApp.operatorid = opco.id WHERE opcoApp.isactive = 1 AND opcoApp.applicationid = ? AND opco.operatorname like ?";

    String approvedOperators = "";

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        ps = conn.prepareStatement(sql);
        ps.setInt(1, applicationId);

        if (operator.equals("__ALL__")) {
            ps.setString(2, "%");
        } else {
            ps.setString(2, operator);
        }

        log.debug("getApprovedOperatorsByApplication");
        rs = ps.executeQuery();
        while (rs.next()) {
            String temp = rs.getString("operatorname");
            approvedOperators = approvedOperators + ", " + temp;
        }
    } catch (Exception e) {
        log.error("Error occured while getting approved operators of application from the database" + e);
    } finally {
        DbUtils.closeAllConnections(ps, conn, rs);
    }
    if (approvedOperators == "") {
        approvedOperators = "NONE";
    } else {
        approvedOperators = approvedOperators.replaceFirst(",", "");
    }

    return approvedOperators;
}

From source file:com.haulmont.cuba.core.sys.dbupdate.ScriptScanner.java

public List<String> getModuleDirs() {
    try {/* ww w  .j  a v  a  2 s . c om*/
        Resource[] resources = createAppropriateResourceResolver()
                .getResources(dbScriptsDirectoryForSearch() + "/**/*.*");
        String dbDirPath = dbScriptDirectoryPath();
        log.trace("DB scripts directory: {}", dbDirPath);
        List<String> modules = Arrays.stream(resources).map(resource -> {
            try {
                String decodedUrl = URLEncodeUtils.decodeUtf8(resource.getURL().toString());
                String resourcePath = decodedUrl.replaceFirst(".+?:", "");
                Matcher matcher = Pattern.compile(".*" + Pattern.quote(dbDirPath) + "/?(.+?)/.*")
                        .matcher(resourcePath);
                return matcher.find() ? matcher.group(1) : null;
            } catch (IOException e) {
                throw new RuntimeException("An error occurred while detecting modules", e);
            }
        }).filter(element -> element != null).collect(Collectors.toSet()).stream().sorted()
                .collect(Collectors.toList());

        if (modules.isEmpty()) {
            throw new RuntimeException(String.format(
                    "No existing modules found. " + "Please check if [%s] contains DB scripts.", dbDirPath));
        }

        log.trace("Found modules: {}", modules);
        return modules;
    } catch (IOException e) {
        throw new RuntimeException("An error occurred while detecting modules", e);
    }
}

From source file:pl.fraanek.caspresentation.client.springsecurity.ProxyTicketSampleServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // NOTE: The CasAuthenticationToken can also be obtained using SecurityContextHolder.getContext().getAuthentication()
    final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
    // proxyTicket could be reused to make calls to to the CAS service even if the target url differs
    final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);

    // Make a remote call to ourself. This is a bit silly, but it works well to demonstrate how to use proxy tickets.
    final String serviceUrl = targetUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8");
    String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");

    // modify the response and write it out to inform the user that it was obtained using a proxy ticket.
    proxyResponse = proxyResponse.replaceFirst("Secure Page", "Secure Page using a Proxy Ticket");
    proxyResponse = proxyResponse.replaceFirst("<p>",
            "<p>This page is rendered by " + getClass().getSimpleName()
                    + " by making a remote call to the Secure Page using a proxy ticket (" + proxyTicket
                    + ") and inserts this message. ");
    final PrintWriter writer = response.getWriter();
    writer.write(proxyResponse);/*from  w  w  w  . j av  a 2 s .com*/
}

From source file:com.blackducksoftware.integration.hub.detect.detector.pip.PipenvGraphParser.java

int getLevel(final String line) {
    String consumableLine = line;
    int level = 0;

    while (consumableLine.startsWith(DEPENDENCY_INDENTATION)) {
        consumableLine = consumableLine.replaceFirst(DEPENDENCY_INDENTATION, "");
        level++;//  w w  w  .j a va 2 s  .co  m
    }

    return level;
}

From source file:net.bluemix.connectors.core.info.IBMGraphDbServiceInfo.java

/**
 * Constructor./* w w  w  . j  a va2 s . c o m*/
 *
 * @param id The id of the service.
 * @param url The URL to the graph DB instance.
 * @throws URISyntaxException Thrown if the URL is malformed.
 */
public IBMGraphDbServiceInfo(final String id, final String url) throws URISyntaxException {
    super(id);
    final URI uri = new URI(url);
    this.apiUrl = url.replaceFirst(IBMGraphDbServiceInfo.SCHEME, "https");
    if (uri.getUserInfo() != null) {
        this.apiUrl = apiUrl.replaceFirst(uri.getUserInfo(), "");
        this.apiUrl = apiUrl.replaceFirst("@", "");
    }
    final String serviceInfoString = uri.getUserInfo();
    if (serviceInfoString != null) {
        String[] userInfo = serviceInfoString.split(":");
        this.username = userInfo[0];
        this.password = userInfo[1];
    }
}

From source file:jp.co.golorp.emarf.properties.collection.AppSet.java

/**
 * @param name/*from   w  w w  .j  ava2  s  .co m*/
 *            ??
 * @return ???suffix?set????
 */
public boolean isEnd(final String name) {

    if (StringUtil.isNotBlank(name)) {
        for (Iterator<?> suffixes = this.iterator(); suffixes.hasNext();) {
            String suffix = (String) suffixes.next();
            if (StringUtils.isNotBlank(suffix) && name.replaceFirst("\\[[0-9]+\\]", "").endsWith(suffix)) {
                return true;
            }
        }
    }

    return false;
}

From source file:com.chilmers.configbootstrapper.ConfigHelper.java

public PropertyResourceBundle getApplicationConfiguration(String applicationConfigLocation) {
    InputStream is = null;//from   w  w  w .j  av a  2  s. c  om
    try {
        if (applicationConfigLocation.startsWith("classpath:")) {
            applicationConfigLocation = applicationConfigLocation.replaceFirst("classpath:", "");
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(applicationConfigLocation);
        } else if (applicationConfigLocation.startsWith("file:")) {
            applicationConfigLocation = applicationConfigLocation.replaceFirst("file:", "");
            is = new FileInputStream(applicationConfigLocation);
        } else {
            logToSystemOut("The application configuration location must start with file: or classpath:");
        }
        return new PropertyResourceBundle(is);

    } catch (Exception e) {
        logToSystemOut("There was a problem reading the application configuration at location: "
                + applicationConfigLocation + "\n" + "Exception:" + e.getClass().toString() + "\n" + "Message:"
                + e.getMessage());
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            logToSystemOut("WARNING! Exception while trying to close configuration file.\n" + "Exception:"
                    + e.getClass().toString() + "\n" + "Message:" + e.getMessage());
        }
    }
    return null;
}