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.github.enr.markdownj.extras.MarkdownApp.java

public void processFile(final File f) {
    String mdFilePath = FileUtils.normalizedPath(f.getAbsolutePath());
    String df = mdFilePath.replaceFirst(source, destination);
    String extension = Files.getFileExtension(df);
    if ((getProcessableExtensions().size() == 0) || (getProcessableExtensions().contains(extension))) {
        String destinationFile = FileUtils.changeExtension(df, ".html");
        log().debug("process '{}' -> '{}'", mdFilePath, destinationFile);
        try {/*  w w  w  .  j a  v a2  s .c o m*/
            String markdownContent = FileUtils.readFileFromPath(mdFilePath, getCharEncoding());
            markdown.setContent(markdownContent);
            String html = markdown.process();
            FileUtils.writeFile(destinationFile, html, getCharEncoding());
        } catch (IOException e) {
            log().warn(e.getMessage(), e);
        }
    } else {
        log().info("Skipping {} (no processable extension '{}')", df, extension);
    }
}

From source file:com.liferay.alloy.taglib.alloy_util.ComponentTag.java

private void _processEventAttribute(String key, String value, Map<String, String> afterEventOptionsMap,
        Map<String, String> onEventsOptionsMap) {

    if (key.startsWith(_AFTER)) {
        String event = StringUtils.uncapitalize(key.replaceFirst(_AFTER, StringPool.BLANK));

        afterEventOptionsMap.put(event, value);
    } else {//from  ww w.j  a  va 2  s  . c  om
        String event = StringUtils.uncapitalize(key.replaceFirst(_ON, StringPool.BLANK));

        onEventsOptionsMap.put(event, value);
    }
}

From source file:io.gumga.presentation.api.voice.VoiceReceiverAPI.java

@RequestMapping(value = "/voice", method = RequestMethod.POST)
public Map recebeSom(HttpServletRequest httpRequest) throws IOException {
    String som = convertStreamToString(httpRequest.getInputStream());
    System.out.println("----->" + som);
    Map<String, Object> problemas = new HashMap<>();
    try {//from w w  w.  ja v a 2 s  .  com
        som = som.replaceFirst("data:audio/wav;base64,", "");
        byte[] decode = Base64.getDecoder().decode(som.substring(0, 512));
        int sampleRate = unsignedToBytes(decode[27]) * 256 * 256 * 256 + unsignedToBytes(decode[26]) * 256 * 256
                + unsignedToBytes(decode[25]) * 256 + unsignedToBytes(decode[24]) * 1;

        RestTemplate restTemplate = new GumgaJsonRestTemplate();
        Map<String, Object> config = new HashMap<>();

        config.put("encoding", "LINEAR16");
        config.put("sampleRate", "" + sampleRate);
        config.put("languageCode", "pt-BR");
        config.put("maxAlternatives", "1");
        config.put("profanityFilter", "false");
        Map<String, Object> context = new HashMap<>();
        context.put("phrases", CONTEXT);
        config.put("speechContext", context); //EXPLORAR DEPOIS COM FRASES PARA "AJUDAR" o reconhecedor
        Map<String, Object> audio = new HashMap<>();
        audio.put("content", som);
        Map<String, Object> request = new HashMap<>();
        request.put("config", config);
        request.put("audio", audio);
        Map resposta = restTemplate.postForObject(
                "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=AIzaSyC7E4dZ4EneRmSzVMs2qhyJYGoTK49FCYM",
                request, Map.class);
        List<Object> analiseSintatica = analiseSintatica(resposta);
        resposta.put("objects", analiseSintatica);
        return resposta;
    } catch (Exception ex) {
        problemas.put("exception", ex);
    }
    return problemas;
}

From source file:pl.com.softproject.altkom.hibernate.forms.web.controller.FormControler.java

@RequestMapping(value = "/saveFormDate", method = RequestMethod.POST)
public String saveFormDate(ServletRequest request, @RequestParam("form_id") long formId) {

    Person person = new Person();

    person.setName(request.getParameter("person.name"));
    person.setAddress(new Address(request.getParameter("person.address.citi"),
            request.getParameter("person.address.street"), request.getParameter("person.address.postcode")));

    personDAO.save(person);// w  w  w .  j a v a  2s  .  com
    Form form = formDAO.findOne(formId);

    FormData formData = new FormData();
    formData.setForm(form);
    formData.setCreationDate(new Date());
    formData.setPerson(person);

    Enumeration<String> params = request.getParameterNames();

    while (params.hasMoreElements()) {
        String param = params.nextElement();

        if (logger.isDebugEnabled())
            logger.debug(param);

        if (param.startsWith("field_")) {
            long fieldId = Long.parseLong(param.replaceFirst("field_", ""));

            FormFieldValue value = new FormFieldValue();
            value.setFieldValue(request.getParameter(param));
            value.setFormData(formData);
            value.setFormField(new FormField(fieldId));
            formData.getAnswers().add(value);
        }
    }

    formDataDAO.save(formData);

    return "redirect:/showForms.htm";
}

From source file:com.funambol.server.SyncMLCanonizer.java

/**
 * Replaces the XML version from any value to "1.0", which is the version
 * supported by our parser. This should not cause any problem since SyncML
 * does not use any XML 1.1 specific feature.
 *
 * @param msg the message to process/*from  w w  w.ja v  a 2 s . co  m*/
 *
 * @return the processed message
 */
private String fixXMLVersion(String msg) {

    if (!msg.startsWith("<?xml")) {
        return msg;
    }

    int e = msg.indexOf("?>");
    if (e < 0) {
        return msg;
    }

    String prolog = msg.substring(0, e + 2);

    if (log.isTraceEnabled()) {
        log.trace("prolog: " + prolog);
    }
    prolog = prolog.replaceFirst("version(\\s)*=[\"'][^\"']+[\"']", "version=\"1.0\"");

    return prolog + msg.substring(e + 2);

}

From source file:com.pcb.pcbridge.commands.CommandBuySkull.java

@Override
public boolean OnExecute(CommandArgs args) {
    if (!args.IsPlayer()) {
        args.GetSender().sendMessage(ChatColor.RED + "Only players in-game can use this command.");
        return true;
    }/*from  w  ww.  j av  a  2  s.  c  om*/

    if (args.GetArgs().length == 0 || args.GetArgs().length > 2)
        return false;

    if (args.GetArgs().length == 2 && !StringUtils.isNumeric(args.GetArg(1)))
        return false;

    // check input for player name
    String alias = args.GetArg(0);

    Matcher m = pattern.matcher(alias);
    if (!m.find())
        return false;

    // strip 'player:' from name
    String name = alias.replaceFirst("^(player:)", "");

    int quantity = args.GetArgs().length == 2 ? Integer.parseInt(args.GetArg(1)) : 1;
    int cost = SKULL_COST * quantity;

    // ensure player has enough money for the purchase
    Economy economy = PCBridge.GetVaultHook().GetEconomy();
    if (!economy.has(args.GetPlayer(), cost)) {
        args.GetSender().sendMessage(ChatColor.RED + "You do not have enough money (price: $" + cost + ")");
        return true;
    }

    // ensure player's inventory isn't full
    PlayerInventory inventory = args.GetPlayer().getInventory();
    if (inventory.firstEmpty() == -1) {
        args.GetSender()
                .sendMessage(ChatColor.RED + "Your inventory is full. Please clear a slot and try again.");
        return true;
    }

    // create skull and give it to the player
    ItemStack skull = new ItemStack(Material.SKULL_ITEM, quantity, (short) 3);
    SkullMeta meta = (SkullMeta) skull.getItemMeta();
    meta.setOwner(name);
    skull.setItemMeta(meta);
    inventory.addItem(skull);

    economy.withdrawPlayer(args.GetPlayer(), cost);

    args.GetSender().sendMessage(ChatColor.GREEN + "Purchased skull of " + name + " for $" + cost);

    return true;
}

From source file:org.jbpm.designer.server.service.DefaultDesignerAssetService.java

private String buildProcessId(String location, String name) {
    if (location.startsWith("/")) {
        location = location.replaceFirst("/", "");
    }/*from   w  ww.  j ava  2 s.co m*/
    location = location.replaceAll("/", ".");

    if (location.length() > 0) {
        String[] locationParts = location.split("\\.");
        location = locationParts[0];
    }

    name = name.substring(0, name.lastIndexOf("."));
    name = Utils.toBPMNIdentifier(name);
    return location + "." + name;
}

From source file:com.twinsoft.convertigo.beans.steps.WriteXMLStep.java

protected void writeFile(String filePath, NodeList nodeList) throws EngineException {
    if (nodeList == null) {
        throw new EngineException("Unable to write to xml file: element is Null");
    }//from  w w  w.  jav a  2  s .  c om

    String fullPathName = getAbsoluteFilePath(filePath);
    synchronized (Engine.theApp.filePropertyManager.getMutex(fullPathName)) {
        try {
            String encoding = getEncoding();
            encoding = encoding.length() > 0 && Charset.isSupported(encoding) ? encoding : "UTF-8";
            if (!isReallyAppend(fullPathName)) {
                String tTag = defaultRootTagname.length() > 0 ? StringUtils.normalize(defaultRootTagname)
                        : "document";
                FileUtils.write(new File(fullPathName),
                        "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n<" + tTag + "/>", encoding);
            }

            StringBuffer content = new StringBuffer();

            /* do the content, only append child element */
            for (int i = 0; i < nodeList.getLength(); i++) {
                if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    content.append(XMLUtils.prettyPrintElement((Element) nodeList.item(i), true, true));
                }
            }

            /* detect current xml encoding */
            RandomAccessFile randomAccessFile = null;
            try {
                randomAccessFile = new RandomAccessFile(fullPathName, "rw");
                FileChannel fc = randomAccessFile.getChannel();
                ByteBuffer buf = ByteBuffer.allocate(60);
                int nb = fc.read(buf);
                String sbuf = new String(buf.array(), 0, nb, "ASCII");
                String enc = sbuf.replaceFirst("^.*encoding=\"", "").replaceFirst("\"[\\d\\D]*$", "");

                if (!Charset.isSupported(enc)) {
                    enc = encoding;
                }

                buf.clear();

                /* retrieve last header tag*/
                long pos = fc.size() - buf.capacity();
                if (pos < 0) {
                    pos = 0;
                }

                nb = fc.read(buf, pos);

                boolean isUTF8 = Charset.forName(enc) == Charset.forName("UTF-8");

                if (isUTF8) {
                    for (int i = 0; i < buf.capacity(); i++) {
                        sbuf = new String(buf.array(), i, nb - i, enc);
                        if (!sbuf.startsWith("")) {
                            pos += i;
                            break;
                        }
                    }
                } else {
                    sbuf = new String(buf.array(), 0, nb, enc);
                }

                int lastTagIndex = sbuf.lastIndexOf("</");
                if (lastTagIndex == -1) {
                    int iend = sbuf.lastIndexOf("/>");
                    if (iend != -1) {
                        lastTagIndex = sbuf.lastIndexOf("<", iend);
                        String tagname = sbuf.substring(lastTagIndex + 1, iend);
                        content = new StringBuffer(
                                "<" + tagname + ">\n" + content.toString() + "</" + tagname + ">");
                    } else {
                        throw new EngineException("Malformed XML file");
                    }
                } else {
                    content.append(sbuf.substring(lastTagIndex));

                    if (isUTF8) {
                        String before = sbuf.substring(0, lastTagIndex);
                        lastTagIndex = before.getBytes(enc).length;
                    }
                }
                fc.write(ByteBuffer.wrap(content.toString().getBytes(enc)), pos + lastTagIndex);
            } finally {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            }
        } catch (IOException e) {
            throw new EngineException("Unable to write to xml file", e);
        } finally {
            Engine.theApp.filePropertyManager.releaseMutex(fullPathName);
        }
    }
}

From source file:com.zextras.modules.chat.ConversationBuilder.java

public void addMessage(ChatMessage chatMessage, Date conversationDate, TimeZone timezone) {
    mConversationDate = conversationDate;
    Date messageDate = chatMessage.getCreationDate();

    String sender = chatMessage.getSender().toString();
    String nickname = sender;//  w w  w  .  j a v  a 2  s .c om

    mSentByMe = sender.equals(mUsername);
    if (!mSentByMe) {
        mSentByMe = sender.equals("Me");
    }
    Boolean isFirstMessage = (!sender.equals(mLastUser) && (mConversation[TEXT_PART].length() > 0));

    if (!mSentByMe) {
        try {
            User user = mOpenUserProvider.getUser(new SpecificAddress(mUsername));
            if (user.hasRelationship(chatMessage.getSender())) {
                Relationship recipient = user.getRelationship(chatMessage.getSender());
                nickname = recipient.getBuddyNickname();
            }
        } catch (ChatDbException ignored) {
        }
    } else {
        nickname = "Me";
    }

    mHourFormatter.setTimeZone(timezone);
    String formattedDate = mHourFormatter.format(messageDate);
    String formattedUser = nickname;

    // remove all [ hour ]. Example: "[ 10:00 ]"
    String conversationText = chatMessage.getBody();
    conversationText = conversationText.replaceFirst("Me:", "");

    // remove all e-mail address + :. Example: "simple@example.com:"
    conversationText = conversationText.replaceFirst("\\[.*?\\] [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+:",
            "");

    String messageHTML;
    messageHTML = StringEscapeUtils.escapeHtml4(conversationText).replaceAll("\n", "<br>");

    appendMessage(conversationText, messageHTML, isFirstMessage, formattedUser, formattedDate);
    mLastUser = formattedUser;
}