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.weibo.datasys.crawler.impl.strategy.rule.seed.ArithmeticListRule.java

@Override
public List<SeedData> apply(Null in) {
    List<SeedData> seedDatas = new ArrayList<SeedData>();
    int maxNum = startNum + diff * (seedCount - 1);
    for (int i = startNum; i <= maxNum; i += diff) {
        for (String baseURL : baseURLs) {
            String url = baseURL.replace(paraPattern, "" + i);
            int indexOfSpace = url.indexOf(" ");
            if (indexOfSpace > 0) {
                url = url.replaceFirst(" ", " " + task.getTaskId() + " ");
            } else {
                url = url + " " + task.getTaskId();
            }//  w w w . ja  va2  s. c  o m
            SeedData seedData = SeedDataFactory.buildFromFormatString(url);
            seedDatas.add(seedData);
        }
    }
    return seedDatas;
}

From source file:net.rptools.gui.listeners.fxml.AbstractURLController.java

/**
 * Add a file to the GUI history section.
 * @param location file name to add/*from  ww  w  .j  a va 2 s .  c o m*/
 * @throws IOException I/O error
 */
@ThreadPolicy(ThreadPolicy.ThreadId.ANY)
public void updateFile(final String location) throws IOException {
    final int historySize = getFileHistorySize();
    final String expandedFileName = Utility.expandEnvironment(location);
    final String probeName = expandedFileName.replaceFirst("file://", "");
    final String name = RptoolsFileTypeDetector.probeContentName(FileSystems.getDefault().getPath(probeName));
    LOGGER.debug("probeName={}; name={}; location={}", probeName, name, location);
    if (name == null || location == null) { // safeguard
        return;
    }
    final AssetTableRow newRow = new AssetTableRow(name, location);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            if (getURLList().getItems().size() == historySize) {
                getURLList().getItems().remove(historySize - 1);
            }
            // This moves existing rows to the front
            if (getURLList().getItems().contains(newRow)) {
                getURLList().getItems().remove(newRow);
            }
            getURLList().getItems().add(0, newRow);
            guiToState();
        }
    });
}

From source file:com.lazerycode.ebselen.handlers.FileHandler.java

public final void setAbsoluteFilename(String value) {
    setFileName(value.replaceFirst("^.*" + sepReg, ""));
    setFilePath(value.substring(0, value.length() - this.fileName.length()));
}

From source file:com.microsoft.azure.management.TestVirtualMachineCustomData.java

@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final String publicIpDnsLabel = SdkContext.randomResourceName("abc", 16);

    // Prepare the custom data
    ///*from ww w.j  a va 2  s. c o  m*/
    String cloudInitFilePath = getClass().getClassLoader().getResource("cloud-init").getPath();
    cloudInitFilePath = cloudInitFilePath.replaceFirst("^/(.:/)", "$1"); // In Windows remove leading slash
    byte[] cloudInitAsBytes = Files.readAllBytes(Paths.get(cloudInitFilePath));
    byte[] cloudInitEncoded = Base64.encodeBase64(cloudInitAsBytes);
    String cloudInitEncodedString = new String(cloudInitEncoded);

    PublicIPAddress pip = pips.define(publicIpDnsLabel).withRegion(Region.US_EAST).withNewResourceGroup()
            .withLeafDomainLabel(publicIpDnsLabel).create();

    VirtualMachine vm = virtualMachines.define(vmName).withRegion(pip.regionName())
            .withExistingResourceGroup(pip.resourceGroupName()).withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(pip)
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!")
            .withCustomData(cloudInitEncodedString).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();

    pip.refresh();
    Assert.assertTrue(pip.hasAssignedNetworkInterface());

    if (!MockIntegrationTestBase.IS_MOCKED) {
        JSch jsch = new JSch();
        Session session = null;
        ChannelExec channel = null;
        try {
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
            session.setPassword("12NewPA$$w0rd!");
            session.setConfig(config);
            session.connect();

            // Try running the package installed via init script
            //
            channel = (ChannelExec) session.openChannel("exec");
            BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            channel.setCommand("pwgen;");
            channel.connect();

            String msg;
            while ((msg = in.readLine()) != null) {
                Assert.assertFalse(msg.startsWith("The program 'pwgen' is currently not installed"));
            }
        } catch (Exception e) {
            Assert.fail("SSH connection failed" + e.getMessage());
        } finally {
            if (channel != null) {
                channel.disconnect();
            }

            if (session != null) {
                session.disconnect();
            }
        }
    }
    return vm;
}

From source file:com.siblinks.ws.service.impl.SibUserDetailServiceImp.java

/**
 * {@inheritDoc}//  w w  w  . j a  va2  s  .c om
 */
@Override
@SuppressWarnings("unchecked")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    LOGGER.debug("Authenticating user with username = {}", username.replaceFirst("@.*", "@.***"));
    SibUser user = null;
    try {
        username = username.replace("'", " ");
        Object[] queryParams = { username };

        List<Object> readObject = dao.readObjects(Parameters.GET_USER_BY_USERNAME, queryParams);

        if (CollectionUtils.isEmpty(readObject)) {
            throw new UsernameNotFoundException(username);
        }

        Map<String, Object> userMap = (Map<String, Object>) readObject.get(0);
        List<GrantedAuthority> authorities = getAuthorities((String) userMap.get(Parameters.USER_TYPE));
        user = new SibUser();
        user.setUsername(username);
        user.setUserid("" + userMap.get(Parameters.USER_ID));
        user.setPassword(
                (userMap.get(Parameters.PASSWORD) != null) ? "" + userMap.get(Parameters.PASSWORD) : null);
        user.setFirstname(
                (userMap.get(Parameters.FIRST_NAME) != null) ? "" + userMap.get(Parameters.FIRST_NAME) : null);
        user.setLastname(
                (userMap.get(Parameters.LAST_NAME) != null) ? "" + userMap.get(Parameters.LAST_NAME) : null);
        user.setUserType(
                (userMap.get(Parameters.USER_TYPE) != null) ? "" + userMap.get(Parameters.USER_TYPE) : null);
        user.setImageUrl(
                (userMap.get(Parameters.IMAGE_URL) != null) ? "" + userMap.get(Parameters.IMAGE_URL) : null);
        user.setSchool((userMap.get(Parameters.SCHOOL) != null) ? "" + userMap.get(Parameters.SCHOOL) : null);
        user.setDefaultSubjectId((userMap.get(Parameters.DEFAULT_SUBJECT_ID) != null)
                ? "" + userMap.get(Parameters.DEFAULT_SUBJECT_ID)
                : null);
        user.setEmail((userMap.get(Parameters.EMAIL) != null) ? "" + userMap.get(Parameters.EMAIL) : null);
        user.setActiveFlag(
                (userMap.get(Parameters.ENABLE_FLAG) != null) ? "" + userMap.get(Parameters.ENABLE_FLAG)
                        : null);
        user.setBirthDay((userMap.get(Parameters.DOB) != null && !"".equals(userMap.get(Parameters.DOB)))
                ? Long.parseLong("" + userMap.get(Parameters.DOB))
                : null);

        return new SibUserDetails(user, authorities);
    } catch (DAOException e) {
        throw new UsernameNotFoundException(e.getMessage());
    }
}

From source file:mx.itesm.imb.EcoreImbEditor.java

/**
 * // w w w  .  ja va2 s .c o m
 * @param templateProject
 */
@SuppressWarnings("unchecked")
public static void createRooApplication(final File ecoreProject, final File busProject,
        final File templateProject) {
    File imbProject;
    File editProject;
    String pluginContent;
    String pomContent;
    String tomcatConfiguration;
    Collection<File> pluginFiles;

    try {
        editProject = new File(ecoreProject.getParent(), ecoreProject.getName() + ".edit");
        imbProject = new File(editProject, "/imb/");
        FileUtils.deleteDirectory(imbProject);

        // Create the roo application
        FileUtils.copyFile(new File(templateProject, "/templates/install.roo"),
                new File(imbProject, "install.roo"));
        EcoreImbEditor.executeCommand("roo script --file install.roo", imbProject);

        // Update libraries
        pomContent = FileUtils.readFileToString(new File(imbProject, "pom.xml"));
        pomContent = pomContent.replaceFirst("</dependencies>",
                FileUtils.readFileToString(new File(templateProject, "/templates/pom.xml")));
        FileUtils.writeStringToFile(new File(imbProject, "pom.xml"), pomContent);

        // IMB types configuration
        FileUtils.copyDirectory(new File(busProject, "/src/main/java/imb"),
                new File(imbProject, "/src/main/java/imb"));
        FileUtils.copyFile(new File(busProject, "/src/main/resources/schema.xsd"),
                new File(imbProject, "/src/main/resources/schema.xsd"));

        FileUtils.copyFile(
                new File(busProject,
                        "/src/main/resources/META-INF/spring/applicationContext-contentresolver.xml"),
                new File(imbProject,
                        "/src/main/resources/META-INF/spring/applicationContext-contentresolver.xml"));

        // Update the plugin configuration
        pluginFiles = FileUtils.listFiles(new File(editProject, "/src"), new IOFileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.getName().endsWith("Plugin.java"));
            }

            @Override
            public boolean accept(File dir, String file) {
                return (file.endsWith("Plugin.java"));
            }
        }, TrueFileFilter.INSTANCE);
        for (File plugin : pluginFiles) {
            pluginContent = FileUtils.readFileToString(plugin);
            pluginContent = pluginContent.substring(0,
                    pluginContent.indexOf("public static class Implementation extends EclipsePlugin"));

            // Tomcat configuration
            tomcatConfiguration = FileUtils
                    .readFileToString(new File(templateProject, "/templates/Plugin.txt"));
            tomcatConfiguration = tomcatConfiguration.replace("${imbProject}", imbProject.getPath());

            FileUtils.writeStringToFile(plugin, pluginContent + tomcatConfiguration);
            break;
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error while configuring Roo application: " + e.getMessage());
    }
}

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

public CloudantServiceInfo(String id, String url) throws URISyntaxException {
    super(id);/*from   w  w w  .j  a v a2  s  . co  m*/
    URI uri = new URI(url);
    this.url = url.replaceFirst(CloudantServiceInfo.SCHEME, "http");
    this.host = uri.getHost();
    this.port = uri.getPort();
    String serviceInfoString = uri.getUserInfo();
    if (serviceInfoString != null) {
        String[] userInfo = serviceInfoString.split(":");
        this.username = userInfo[0];
        this.password = userInfo[1];
    }
}

From source file:org.ecside.common.H2DriverManagerDataSource.java

public void setDefaultDB(String defaultDB) {
    if (!StringUtils.hasText(defaultDB)) {
        throw new IllegalArgumentException("url must not be empty");
    }//from w w  w.  j  a  v a  2  s  . c  om
    this.defaultDB = defaultDB.replaceFirst(C_RootRealPath, rootRealPath).trim();
}

From source file:com.nts.alphamale.monitor.HierarchyMonitor.java

private void getHierarchyDump() {
    log.info("getHierarchyDump");
    long dumpTime = System.currentTimeMillis();
    String hierchary = DeviceHandler.createDump(serial);
    if (StringUtils.isNotEmpty(hierchary) && hierchary.contains("hierarchy rotation")) {
        hierchary = hierchary.replaceFirst("hierarchy rotation",
                "hierarchy time=\"" + dumpTime + "\" rotation");
        try {//from   ww  w.j av  a 2 s . c  om
            Document doc = DocumentHandler.convertStringToDocument(hierchary);
            if (DataQueue.DOCUMENT_QUEUE.size() == 3)
                DataQueue.DOCUMENT_QUEUE.poll();
            DataQueue.DOCUMENT_QUEUE.offer(doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:de.codecentric.boot.admin.model.Application.java

@JsonCreator
public Application(@JsonProperty(value = "url", required = true) String url,
        @JsonProperty(value = "name", required = true) String name, @JsonProperty("id") String id) {
    this.url = url.replaceFirst("/+$", "");
    this.name = name;
    this.id = id;
}