Question

So my goal here is to create a URL shortener and it is working except when I enter two URLs in one line.

So for example, if I enter "laskjdflas www.google.com lakdsjfsa www.google.ca" I get this in response:

Please enter in a URL to shorten

laskjdf www.google.ca lksadjf www.google.com

laskjdf http://aman207.tk/9 lksadjf http://aman207.tk/9

laskjdf htt://aman207.tk/-4gi5 lksadjf htt://aman207.tk/-4gi5

(I know those last two links are missing a p)

This is my code:

Scanner keyboard=new Scanner(System.in);
System.out.println("Please enter in a URL to shorten");
URLget=keyboard.nextLine();
String originalMessage=URLget;

Pattern p = Pattern.compile("(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))");
Matcher m = p.matcher(URLget);
StringBuffer sb = new StringBuffer();
while (m.find())
{
   URLget=m.group(1);
   m.appendReplacement(sb, "");
   sb.append(URLget);
   m.appendTail(sb);
   String URL="http://www.aman207.tk/yourls-api.php?signature=0a88314b95&action=shorturl&url="+ URLget;
   if (URLget.startsWith("http://")||URLget.startsWith("www."))
   {
       try {
           DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
           DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
           Document doc = docBuilder.parse(new InputSource(new URL(URL).openStream()));

           NodeList nodeList = doc.getElementsByTagName("shorturl");

           for (int temp = 0; temp < nodeList.getLength(); temp++)
           {
               Node nNode = nodeList.item(temp);
               Element eElement = (Element) nNode;
               if(eElement.getAttribute("shorturl") != null)
               {
                   String findShortURL= eElement.getTextContent();
                   String finalMessage = originalMessage.replaceAll("(?:http://|www.?)[\\w/%.-]+", findShortURL);
                   System.out.println(finalMessage);
               }
            }
        }
    }
}

What I need for it to do, it to replace each URL on one line. Does anybody have any suggestions? Thanks!

EDIT:

Input: Random words [URL to shorten (URL 1)] more random words [URL to shorten (URL 2)]

Output:

Same random words [Shortened URL 1] same random words [Shortened URL 1 (It is the same shortened URL as the first URL. I need it to be like the expected output)]

Expected Output:

Same random words [Shortened URL 1] same random words [Shortened URL 2]

Was it helpful?

Solution 2

I figured it out myself.

This is the working code

Pattern p = Pattern.compile("(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))");
Matcher m = p.matcher(URLget);
StringBuffer sb = new StringBuffer();  
while (m.find())  
     {  
        URLget=m.group(1);  
        String URL="http://www.aman207.tk/yourls-api.php?signature=0a88314b95&action=shorturl&url="+ URLget;
        if (URLget.startsWith("http://")||URLget.startsWith("www."))
    {
        try {               
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new InputSource(new URL(URL).openStream()));

            NodeList nodeList = doc.getElementsByTagName("shorturl");

            for (int temp = 0; temp < nodeList.getLength(); temp++) {

                Node nNode = nodeList.item(temp);
                Element eElement = (Element) nNode;
                if(eElement.getAttribute("shorturl") != null)
                {
                    URLget=eElement.getTextContent();

                }
                else
                {

                }

            }

    }

       catch (IOException e) {
        e.printStackTrace();
        System.err.println("Error occured");
    }  catch (SAXException e) {
        System.err.println("You either entered in an invalid URL, or our URL shortener services are down. Please try again.");
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    }
    else
    {

    }
    m.appendReplacement(sb, "");
    sb.append(URLget);

     }
    m.appendTail(sb);
    return (sb.toString());

OTHER TIPS

Replace your if statement with this :

if(eElement.getAttribute("shorturl") != null)
{                      
    String findShortURL= eElement.getTextContent();
    originalMessage = originalMessage.replaceAll(URLget, findShortURL);
    System.out.println(originalMessage);
}

Use println outside the for loop to get it to give you the output just once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top