de.huxhorn.whistler.services.RealurlUrlUnshortener.java Source code

Java tutorial

Introduction

Here is the source code for de.huxhorn.whistler.services.RealurlUrlUnshortener.java

Source

/*
 * Whistler - it's about microblogging.
 * Copyright (C) 2009-2010 Joern Huxhorn
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.huxhorn.whistler.services;

import com.ctc.wstx.stax.WstxInputFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.codehaus.stax2.XMLStreamReader2;

import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class RealurlUrlUnshortener implements UrlUnshortener {
    private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RealurlUrlUnshortener.class);

    public String unshorten(String url) {

        XMLStreamReader2 xmlStreamReader = null;
        try {
            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            // http://realurl.org/api/v1/getrealurl.php?url=
            qparams.add(new BasicNameValuePair("url", url));
            BasicHttpParams params = new BasicHttpParams();

            DefaultHttpClient httpclient = new DefaultHttpClient(params);

            URI uri = URIUtils.createURI("http", "realurl.org", -1, "/api/v1/getrealurl.php",
                    URLEncodedUtils.format(qparams, "UTF-8"), null);
            HttpGet httpget = new HttpGet(uri);
            if (logger.isDebugEnabled())
                logger.debug("HttpGet.uri={}", httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                xmlStreamReader = (XMLStreamReader2) WstxInputFactory.newInstance().createXMLStreamReader(instream);

                /*
                <root>
                  <status>1</status>
                  <url>
                     <short>http://bit.ly/10QRTY</short>
                     <real>
                     http://uk.techcrunch.com/2009/04/09/tweetmeme-re-launches-to-gun-for-top-of-the-twitter-link-tree/
                     </real>
                  </url>
                </root>
                 */
                while (xmlStreamReader.hasNext()) {
                    int type = xmlStreamReader.next();
                    if (type == XMLStreamConstants.START_ELEMENT) {
                        if ("real".equals(xmlStreamReader.getName().getLocalPart())) {
                            return xmlStreamReader.getElementText();
                        }
                    }
                }
                /*
                BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
                StringBuilder builder=new StringBuilder();
                for(;;)
                {
                   String line = reader.readLine();
                   if(line == null)
                   {
                      break;
                   }
                   if(builder.length() != 0)
                   {
                      builder.append("\n");
                   }
                   builder.append(line);
                }
                if(logger.isInfoEnabled()) logger.info("Result: {}", builder);
                */
            }
        } catch (IOException ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception!", ex);
        } catch (URISyntaxException ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception!", ex);
        } catch (XMLStreamException ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception!", ex);
        } finally {
            if (xmlStreamReader != null) {
                try {
                    xmlStreamReader.closeCompletely();
                } catch (XMLStreamException e) {
                    // ignore
                }
            }
        }
        return null;
    }

}