Example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Click Source Link

Document

<tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.gots.server.auth.TempTokenAuthenticationServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Get request parameters
    String applicationName = req.getParameter(APPLICATION_NAME_PARAM);
    String deviceId = req.getParameter(DEVICE_ID_PARAM);
    String deviceDescription = req.getParameter(DEVICE_DESCRIPTION_PARAM);
    String permission = req.getParameter(PERMISSION_PARAM);
    String revokeParam = req.getParameter(REVOKE_PARAM);
    boolean revoke = Boolean.valueOf(revokeParam);

    // If one of the required parameters is null or empty, send an
    // error with the 400 status
    if (!revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId)
            || StringUtils.isEmpty(permission))) {
        log.error(//from ww  w  .j a v  a  2  s.  c  o m
                "The following request parameters are mandatory to acquire an authentication token: applicationName, deviceId, permission.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }
    if (revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId))) {
        log.error(
                "The following request parameters are mandatory to revoke an authentication token: applicationName, deviceId.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    // Decode parameters
    applicationName = URIUtil.decode(applicationName);
    deviceId = URIUtil.decode(deviceId);
    if (!StringUtils.isEmpty(deviceDescription)) {
        deviceDescription = URIUtil.decode(deviceDescription);
    }
    if (!StringUtils.isEmpty(permission)) {
        permission = URIUtil.decode(permission);
    }

    // Get user name from request Principal
    Principal principal = req.getUserPrincipal();
    if (principal == null) {
        resp.sendError(HttpStatus.SC_UNAUTHORIZED);
        return;
    }
    String userName = principal.getName();
    log.error("The principal user is " + userName);
    // Write response
    String response = null;
    TokenAuthenticationService tokenAuthService = Framework.getLocalService(TokenAuthenticationService.class);
    try {
        // Token acquisition: acquire token and write it to the response
        // body
        if (!revoke) {
            response = tokenAuthService.acquireToken(userName, applicationName, deviceId, deviceDescription,
                    permission);
        }
        // Token revocation
        else {
            String token = tokenAuthService.getToken(userName, applicationName, deviceId);
            if (token == null) {
                response = String.format(
                        "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.",
                        userName, applicationName, deviceId);
            } else {
                tokenAuthService.revokeToken(token);
                response = String.format("Token revoked for userName %s, applicationName %s and deviceId %s.",
                        userName, applicationName, deviceId);
            }
        }
        sendTextResponse(resp, response);
    } catch (Exception e) {
        // Should never happen as parameters have already been checked
        resp.sendError(HttpStatus.SC_NOT_FOUND);
    }
}

From source file:org.jahia.test.services.render.JSessionIDTest.java

private void findJSessionId(boolean removeJsessionId) throws IOException {
    SettingsBean.getInstance().setDisableJsessionIdParameter(removeJsessionId);
    SettingsBean.getInstance().setJsessionIdParameterName(jsessionid);

    GetMethod displayLoginMethod = new GetMethod(getBaseServerURL() + Jahia.getContextPath() + "/start");
    try {/*from   w w w  .  j a va  2 s.  com*/
        int statusCode = httpClient.executeMethod(displayLoginMethod);

        assertEquals("Method failed: " + displayLoginMethod.getStatusLine(), HttpStatus.SC_UNAUTHORIZED,
                statusCode);

        String responseBodyAsString = displayLoginMethod.getResponseBodyAsString();

        Pattern p = Pattern.compile("action=\"([^\"]*)\"");
        Matcher m = p.matcher(responseBodyAsString);
        assertTrue(m.find());

        String url = m.group(1);
        if (!removeJsessionId) {
            logger.info("Unencoded URL: " + getBaseServerURL() + Jahia.getContextPath() + "/start");
            logger.info("Encoded redirect URL: "
                    + getResponse().encodeRedirectURL(getBaseServerURL() + Jahia.getContextPath() + "/start"));
            logger.info("Encoded URL: "
                    + getResponse().encodeURL(getBaseServerURL() + Jahia.getContextPath() + "/start"));
        }

        assertEquals(
                "jsession ID is not " + (removeJsessionId ? "removed" : "present")
                        + " in administration login url:" + url,
                removeJsessionId, !StringUtils.containsIgnoreCase(url, jsessionid));
    } finally {
        displayLoginMethod.releaseConnection();
    }
}

From source file:org.jetbrains.plugins.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;//from   w  ww.  j  av  a 2 s .c o  m
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        throw new GithubAuthenticationException("Request response: " + getErrorMessage(method));
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:org.jetbrains.tfsIntegration.exceptions.TfsExceptionManager.java

public static TfsException createHttpTransportErrorException(int errorCode, AxisFault axisFault) {
    switch (errorCode) {
    case HttpStatus.SC_UNAUTHORIZED:
        return new UnauthorizedException(axisFault);
    case HttpStatus.SC_BAD_GATEWAY:
        return new HostNotFoundException(axisFault);
    case HttpStatus.SC_NOT_FOUND:
        return new HostNotApplicableException(axisFault);
    case HttpStatus.SC_FORBIDDEN:
        return new ForbiddenException(axisFault);
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        return new TfsException(TFSBundle.message("proxy.auth.failed"));
    default://from  ww w  .  j av  a 2s.c o m
        return new ConnectionFailedException(axisFault, errorCode);
    }
}

From source file:org.methodize.nntprss.admin.AdminServlet.java

private void cmdUpdateChannel(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Writer writer = response.getWriter();
    writeHeader(writer, TAB_VIEW_CHANNELS);

    String channelName = request.getParameter("name");

    ChannelManager channelManager = (ChannelManager) getServletContext()
            .getAttribute(AdminServer.SERVLET_CTX_RSS_MANAGER);

    Channel channel = channelManager.channelByName(channelName);

    if (request.getParameter("update") != null) {
        // Update channel.
        String urlString = request.getParameter("URL");
        List errors = new ArrayList();
        if (urlString.length() == 0) {
            errors.add("URL cannot be empty");
        } else if (urlString.equals("http://") || urlString.equals("https://")) {
            errors.add("You must specify a URL");
        } else if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
            errors.add("Only URLs starting http:// or https:// are supported");
        }/*from w  w  w.  jav a 2 s  .c o m*/

        boolean postingEnabled = request.getParameter("postingEnabled").equalsIgnoreCase("true");
        String publishAPI = null;
        Map publishConfig = null;
        if (postingEnabled) {
            publishConfig = new HashMap();
            publishAPI = request.getParameter("publishAPI");

            // Validate...
            //TODO: improve componentization / pluggability of publishers
            if (publishAPI.equals("blogger")) {
                publishConfig.put(BloggerPublisher.PROP_PUBLISHER_URL,
                        request.getParameter(BloggerPublisher.PROP_PUBLISHER_URL));
                publishConfig.put(BloggerPublisher.PROP_USERNAME,
                        request.getParameter(BloggerPublisher.PROP_USERNAME));

                String password = request.getParameter(BloggerPublisher.PROP_PASSWORD);
                if (password.equals(PASSWORD_MAGIC_KEY) && (channel.getPublishConfig() != null)) {
                    password = (String) channel.getPublishConfig().get(BloggerPublisher.PROP_PASSWORD);
                }
                publishConfig.put(BloggerPublisher.PROP_PASSWORD, password);

                publishConfig.put(BloggerPublisher.PROP_BLOG_ID,
                        request.getParameter(BloggerPublisher.PROP_BLOG_ID));

                String autoPublishStr = (String) request.getParameter(BloggerPublisher.PROP_PUBLISH);
                if (autoPublishStr.equals("true")) {
                    publishConfig.put(BloggerPublisher.PROP_PUBLISH, "true");
                } else {
                    publishConfig.put(BloggerPublisher.PROP_PUBLISH, "false");
                }

                try {
                    Publisher pub = new BloggerPublisher();
                    pub.validate(publishConfig);
                } catch (PublisherException pe) {
                    errors.add("Error validating Blogger posting configuration - " + pe.getMessage());
                    errors.add("Check Blogger URL, user name, password, and blog id.");
                }

            } else if (publishAPI.equals("metaweblog")) {
                publishConfig.put(MetaWeblogPublisher.PROP_PUBLISHER_URL,
                        request.getParameter(MetaWeblogPublisher.PROP_PUBLISHER_URL));
                publishConfig.put(MetaWeblogPublisher.PROP_USERNAME,
                        request.getParameter(MetaWeblogPublisher.PROP_USERNAME));

                String password = request.getParameter(MetaWeblogPublisher.PROP_PASSWORD);
                if (password.equals(PASSWORD_MAGIC_KEY) && (channel.getPublishConfig() != null)) {
                    password = (String) channel.getPublishConfig().get(MetaWeblogPublisher.PROP_PASSWORD);
                }
                publishConfig.put(MetaWeblogPublisher.PROP_PASSWORD, password);

                publishConfig.put(MetaWeblogPublisher.PROP_BLOG_ID,
                        request.getParameter(MetaWeblogPublisher.PROP_BLOG_ID));

                String autoPublishStr = (String) request.getParameter(MetaWeblogPublisher.PROP_PUBLISH);
                if (autoPublishStr.equals("true")) {
                    publishConfig.put(MetaWeblogPublisher.PROP_PUBLISH, "true");
                } else {
                    publishConfig.put(MetaWeblogPublisher.PROP_PUBLISH, "false");
                }

                try {
                    Publisher pub = new MetaWeblogPublisher();
                    pub.validate(publishConfig);
                } catch (PublisherException pe) {
                    errors.add("Error validating MetaWeblog posting configuration - " + pe.getMessage());
                    errors.add("Check URL, user name, and password.");
                }

            } else if (publishAPI.equals("livejournal")) {
                publishConfig.put(LiveJournalPublisher.PROP_PUBLISHER_URL,
                        request.getParameter(LiveJournalPublisher.PROP_PUBLISHER_URL));
                publishConfig.put(LiveJournalPublisher.PROP_USERNAME,
                        request.getParameter(LiveJournalPublisher.PROP_USERNAME));

                String password = request.getParameter(LiveJournalPublisher.PROP_PASSWORD);
                if (password.equals(PASSWORD_MAGIC_KEY) && (channel.getPublishConfig() != null)) {
                    password = (String) channel.getPublishConfig().get(LiveJournalPublisher.PROP_PASSWORD);
                }
                publishConfig.put(LiveJournalPublisher.PROP_PASSWORD, password);

                try {
                    Publisher pub = new LiveJournalPublisher();
                    pub.validate(publishConfig);
                } catch (PublisherException pe) {
                    errors.add("Error validating LiveJournal posting configuration - " + pe.getMessage());
                    errors.add("Check LiveJournal URL, user name, and password.");
                }
            }

        }

        if (errors.size() == 0) {
            try {
                boolean parseAtAllCost = isChecked(request, "parseAtAllCost");
                boolean enabled = isChecked(request, "enabled");
                boolean valid = true;

                URL url = new URL(urlString);
                if (!parseAtAllCost && enabled) {
                    try {
                        valid = Channel.isValid(url);
                        if (!valid) {
                            errors.add("URL does not point to valid RSS or ATOM document");
                            errors.add("<a target='validate' href='http://feedvalidator.org/check?url="
                                    + urlString
                                    + "'>Check the URL with the RSS and ATOM Validator @ archive.org</a><br>");
                        }
                    } catch (HttpUserException hue) {
                        if (hue.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
                            errors.add(
                                    "This feed requires user name and password authentication.  Please specify User Name and Password in the URL, e.g.");
                            errors.add("http://username:password@www.myhost.com/");
                        } else if (hue.getStatus() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                            errors.add("You are using a proxy server that requires authentication.");
                            errors.add(
                                    "Please enter your User Name and Password in the <a href='?action=showconfig'>System Configuration.</a>");
                        }
                        valid = false;
                    }
                }

                if (valid) {
                    channel.setUrl(url);
                    //                  channel.setHistorical(isChecked(request, "historical"));
                    channel.setExpiration(Long.parseLong(request.getParameter("expiration")));

                    int categoryId = Integer.parseInt(request.getParameter("categoryId"));
                    boolean categoryChanged = ((!(categoryId == 0 && channel.getCategory() == null))
                            && ((categoryId != 0 && channel.getCategory() == null)
                                    || (categoryId != channel.getCategory().getId())));
                    Category oldCategory = channel.getCategory();

                    channel.setEnabled(enabled);
                    channel.setParseAtAllCost(parseAtAllCost);

                    channel.setPostingEnabled(postingEnabled);
                    channel.setPublishAPI(publishAPI);
                    channel.setPublishConfig(publishConfig);

                    channel.setPollingIntervalSeconds(Long.parseLong(request.getParameter("pollingInterval")));

                    if (categoryChanged) {
                        Category category = null;
                        if (oldCategory != null) {
                            oldCategory.removeChannel(channel);
                        }
                        if (categoryId != 0) {
                            category = channelManager.categoryById(categoryId);
                            category.addChannel(channel);
                        }
                        channel.setCategory(category);
                    }

                    channel.save();

                    if (enabled) {
                        // Reset status and last polled date - channel should
                        // get repolled on next iteration
                        channel.setStatus(Channel.STATUS_OK);
                        channel.setLastPolled(null);
                    }
                }
            } catch (MalformedURLException me) {
                errors.add("URL is malformed");
            }
        }

        if (errors.size() == 0) {
            writer.write("Channel <b>" + channel.getName() + "</b> successfully updated.<p>");
            writeChannel(writer, channel, request, false);
        } else {
            writer.write("<b>There were errors updating the channel:</b><p>");
            writeErrors(writer, errors);
            writeChannel(writer, channel, request, true);
        }

    } else if (request.getParameter("delete") != null) {
        channelManager.deleteChannel(channel);
        writer.write("Channel <b>" + channel.getName() + "</b> successfully deleted.");
    }

    writeFooter(writer);
}

From source file:org.methodize.nntprss.admin.AdminServlet.java

private void cmdAddChannel(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ChannelManager channelManager = (ChannelManager) getServletContext()
            .getAttribute(AdminServer.SERVLET_CTX_RSS_MANAGER);

    NNTPServer nntpServer = (NNTPServer) getServletContext().getAttribute(AdminServer.SERVLET_CTX_NNTP_SERVER);

    String name = request.getParameter("name").trim();
    String urlString = request.getParameter("url").trim();
    //      boolean historical = isChecked(request, "historical");
    boolean validate = isChecked(request, "validate");
    long expiration = Long.parseLong(request.getParameter("expiration"));
    int categoryId = Integer.parseInt(request.getParameter("categoryId"));

    List errors = new ArrayList();
    if (name.length() == 0) {
        errors.add("Name cannot be empty");
    } else if (name.indexOf(' ') > -1) {
        errors.add("Name cannot contain spaces");
    } else if (channelManager.channelByName(name) != null || channelManager.categoryByName(name) != null) {
        errors.add("Name is already is use");
    }//from  w w  w. ja v a  2  s  . c o m

    if (urlString.length() == 0) {
        errors.add("URL cannot be empty");
    } else if (urlString.equals("http://") || urlString.equals("https://")) {
        errors.add("You must specify a URL");
    } else if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
        errors.add("Only URLs starting http:// or https:// are supported");
    }

    Channel newChannel = null;
    if (errors.size() == 0) {
        try {
            newChannel = new Channel(name, urlString);
            //            newChannel.setHistorical(historical);
            newChannel.setExpiration(expiration);
            if (validate && !newChannel.isValid()) {
                errors.add("URL does not point to valid RSS or ATOM document");
                errors.add("<a target='validate' href='http://feedvalidator.org/check?url=" + urlString
                        + "'>Check the URL with the RSS and ATOM Validator @ archive.org</a>");
                newChannel = null;
            }
        } catch (HttpUserException hue) {
            if (hue.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
                errors.add("This feed requires user name and password authentication.");
                errors.add("Please specify User Name and Password in the URL, e.g.");
                errors.add("http://username:password@www.myhost.com/");
            } else if (hue.getStatus() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                errors.add("You are using a proxy server that requires authentication.");
                errors.add(
                        "Please enter your User Name and Password in the <a href='?action=showconfig'>System Configuration.</a>");
            }
        } catch (MalformedURLException me) {
            errors.add("URL is malformed (" + me.getLocalizedMessage() + ")");
        }
    }

    Writer writer = response.getWriter();
    writeHeader(writer, TAB_ADD_CHANNEL);

    if (errors.size() > 0) {
        writer.write("<b>There were errors adding your channel:</b><p>");
        writeErrors(writer, errors);
        writer.write("<p>");
        writer.write("<form action='/?action=add' method='post'>");
        writer.write("<table class='tableborder'>");

        writer.write("<tr><th colspan='2'>Add Channel</th></tr>");
        writer.write(
                "<tr><td class='row1' align='right'>Newsgroup Name:</td><td class='row2'><input type='text' name='name' size='64' value='"
                        + HTMLHelper.escapeString(name) + "'></td></tr>");
        writer.write(
                "<tr><td class='row1' align='right'>Feed URL:</td><td class='row2'><input type='text' name='url' size='64' value='"
                        + HTMLHelper.escapeString(urlString)
                        + "'><br><i>(nntp//rss supports both RSS and ATOM feeds)</i></td></tr>");

        //         writer.write("<tr><td class='row1' align='right' valign='top'>Historical</td><td class='row2'><input type='checkbox' value='true' name='historical' "
        //            + (historical ? "checked" : "")
        //            + ">"
        //            + "<br><i>(Checked = Keep items removed from the original RSS document)</i></td></tr>");

        writer.write("<tr><td class='row1' align='right' valign='top'>Item Expiration</td><td class='row2'>");

        writer.write("<select name='expiration'>");
        writeOption(writer, "Keep all items", Channel.EXPIRATION_KEEP, expiration);
        writeOption(writer, "Keep only current items", 0, expiration);
        writeOption(writer, "Keep items for 1 day", (1000 * 60 * 60 * 24 * 1), expiration);
        writeOption(writer, "Keep items for 2 days", (1000 * 60 * 60 * 24 * 2), expiration);
        writeOption(writer, "Keep items for 4 days", (1000 * 60 * 60 * 24 * 4), expiration);
        writeOption(writer, "Keep items for 1 week", (1000 * 60 * 60 * 24 * 7), expiration);
        writeOption(writer, "Keep items for 2 weeks", (1000 * 60 * 60 * 24 * 14), expiration);
        writeOption(writer, "Keep items for 4 weeks", (1000 * 60 * 60 * 24 * 28), expiration);

        writer.write("</select></td></tr>");

        writer.write(
                "<tr><td class='row1' align='right' valign='top'>Validate</td><td class='row2'><input type='checkbox'  value='true' name='validate' "
                        + (validate ? "checked" : "") + ">"
                        + "<br><i>(Checked = Ensure URL points to a valid RSS document)</i></td></tr>");

        writer.write("<tr><td class='row1' align='right'>Category</td>");
        writer.write("<td class='row2'><select name='categoryId'>");

        writeOption(writer, "[No Category]", 0, categoryId);
        Iterator categories = channelManager.categories();
        while (categories.hasNext()) {
            Category category = (Category) categories.next();
            writeOption(writer, category.getName(), category.getId(), categoryId);
        }
        writer.write("</select></td></tr>");

        writer.write(
                "<tr><td class='row2' align='center' colspan='2'><input type='submit' value='Add'> <input type='reset'></td></tr></table>");
        writer.write("</form>");
    } else {
        channelManager.addChannel(newChannel);
        if (categoryId != 0) {
            Category category = channelManager.categoryById(categoryId);
            category.addChannel(newChannel);
            newChannel.setCategory(category);
            newChannel.save();
        }

        writer.write("Channel " + newChannel.getName() + " successfully added.<p>");

        writer.write("<a href='" + getNewsURLPrefix(nntpServer) + newChannel.getName() + "'>"
                + "[View the channel in your newsreader]</a>");
    }

    writeFooter(writer);
    writer.flush();

}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Retrieves the latest RSS doc from the remote site
 *//*from w ww.j  a v  a  2s  . co m*/
public synchronized void poll() {
    // Use method-level variable
    // Guard against change in history mid-poll
    polling = true;

    //      boolean keepHistory = historical;
    long keepExpiration = expiration;

    lastPolled = new Date();

    int statusCode = -1;
    HttpMethod method = null;
    String urlString = url.toString();
    try {
        HttpClient httpClient = getHttpClient();
        channelManager.configureHttpClient(httpClient);
        HttpResult result = null;

        try {

            connected = true;
            boolean redirected = false;
            int count = 0;
            do {
                URL currentUrl = new URL(urlString);
                method = new GetMethod(urlString);
                method.setRequestHeader("User-agent", AppConstants.getUserAgent());
                method.setRequestHeader("Accept-Encoding", "gzip");
                method.setFollowRedirects(false);
                method.setDoAuthentication(true);

                // ETag
                if (lastETag != null) {
                    method.setRequestHeader("If-None-Match", lastETag);
                }

                // Last Modified
                if (lastModified != 0) {
                    final String NAME = "If-Modified-Since";
                    //defend against such fun like net.freeroller.rickard got If-Modified-Since "Thu, 24 Aug 2028 12:29:54 GMT"
                    if (lastModified < System.currentTimeMillis()) {
                        final String DATE = httpDate.format(new Date(lastModified));
                        method.setRequestHeader(NAME, DATE);
                        log.debug("channel " + this.name + " using " + NAME + " " + DATE); //ALEK
                    }
                }

                method.setFollowRedirects(false);
                method.setDoAuthentication(true);

                HostConfiguration hostConfig = new HostConfiguration();
                hostConfig.setHost(currentUrl.getHost(), currentUrl.getPort(), currentUrl.getProtocol());

                result = executeHttpRequest(httpClient, hostConfig, method);
                statusCode = result.getStatusCode();
                if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                        || statusCode == HttpStatus.SC_SEE_OTHER
                        || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {

                    redirected = true;
                    // Resolve against current URI - may be a relative URI
                    try {
                        urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                    } catch (URISyntaxException use) {
                        // Fall back to just using location from result
                        urlString = result.getLocation();
                    }
                    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY && channelManager.isObserveHttp301()) {
                        try {
                            url = new URL(urlString);
                            if (log.isInfoEnabled()) {
                                log.info("Channel = " + this.name
                                        + ", updated URL from HTTP Permanent Redirect");
                            }
                        } catch (MalformedURLException mue) {
                            // Ignore URL permanent redirect for now...                        
                        }
                    }
                } else {
                    redirected = false;
                }

                //               method.getResponseBody();
                //               method.releaseConnection();
                count++;
            } while (count < 5 && redirected);

        } catch (HttpRecoverableException hre) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Temporary Http Problem - " + hre.getMessage());
            }
            status = STATUS_CONNECTION_TIMEOUT;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (ConnectException ce) {
            // @TODO Might also be a connection refused - not only a timeout...
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Connection Timeout, skipping - " + ce.getMessage());
            }
            status = STATUS_CONNECTION_TIMEOUT;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (UnknownHostException ue) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Unknown Host Exception, skipping");
            }
            status = STATUS_UNKNOWN_HOST;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (NoRouteToHostException re) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - No Route To Host Exception, skipping");
            }
            status = STATUS_NO_ROUTE_TO_HOST;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (SocketException se) {
            // e.g. Network is unreachable            
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Socket Exception, skipping");
            }
            status = STATUS_SOCKET_EXCEPTION;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        }

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (connected && statusCode == HttpStatus.SC_OK) {

            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);
            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();

            try {
                Document rssDoc = null;
                if (!parseAtAllCost) {
                    try {
                        rssDoc = db.parse(bis);
                    } catch (InternalError ie) {
                        // Crimson library throws InternalErrors
                        if (log.isDebugEnabled()) {
                            log.debug("InternalError thrown by Crimson", ie);
                        }
                        throw new SAXException("InternalError thrown by Crimson: " + ie.getMessage());
                    }
                } else {
                    // Parse-at-all-costs selected
                    // Read in document to local array - may need to parse twice
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int bytesRead = bis.read(buf);
                    while (bytesRead > -1) {
                        if (bytesRead > 0) {
                            bos.write(buf, 0, bytesRead);
                        }
                        bytesRead = bis.read(buf);
                    }
                    bos.flush();
                    bos.close();

                    byte[] rssDocBytes = bos.toByteArray();

                    try {
                        // Try the XML document parser first - just in case
                        // the doc is well-formed
                        rssDoc = db.parse(new ByteArrayInputStream(rssDocBytes));
                    } catch (SAXParseException spe) {
                        if (log.isDebugEnabled()) {
                            log.debug("XML parse failed, trying tidy");
                        }
                        // Fallback to parse-at-all-costs parser
                        rssDoc = LooseParser.parse(new ByteArrayInputStream(rssDocBytes));
                    }
                }

                processChannelDocument(expiration, rssDoc);

                // Update last modified / etag from headers
                //               lastETag = httpCon.getHeaderField("ETag");
                //               lastModified = httpCon.getHeaderFieldDate("Last-Modified", 0);

                Header hdrETag = method.getResponseHeader("ETag");
                lastETag = hdrETag != null ? hdrETag.getValue() : null;

                Header hdrLastModified = method.getResponseHeader("Last-Modified");
                lastModified = hdrLastModified != null ? parseHttpDate(hdrLastModified.getValue()) : 0;
                log.debug("channel " + this.name + " parsed Last-Modifed " + hdrLastModified + " to "
                        + (lastModified != 0 ? "" + (new Date(lastModified)) : "" + lastModified)); //ALEK

                status = STATUS_OK;
            } catch (SAXParseException spe) {
                if (log.isEnabledFor(Priority.WARN)) {
                    log.warn("Channel=" + name + " - Error parsing RSS document - check feed");
                }
                status = STATUS_INVALID_CONTENT;
            }

            bis.close();

            // end if response code == HTTP_OK
        } else if (connected && statusCode == HttpStatus.SC_NOT_MODIFIED) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - HTTP_NOT_MODIFIED, skipping");
            }
            status = STATUS_OK;
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            if (log.isEnabledFor(Priority.WARN)) {
                log.warn("Channel=" + name + " - Proxy authentication required");
            }
            status = STATUS_PROXY_AUTHENTICATION_REQUIRED;
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            if (log.isEnabledFor(Priority.WARN)) {
                log.warn("Channel=" + name + " - Authentication required");
            }
            status = STATUS_USER_AUTHENTICATION_REQUIRED;
        }

        // Update channel in database...
        channelDAO.updateChannel(this);

    } catch (FileNotFoundException fnfe) {
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - File not found returned by web server - check feed");
        }
        status = STATUS_NOT_FOUND;
    } catch (Exception e) {
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - Exception while polling channel", e);
        }
    } catch (NoClassDefFoundError ncdf) {
        // Throw if SSL / redirection to HTTPS
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - NoClassDefFound", ncdf);
        }
    } finally {
        connected = false;
        polling = false;
    }

}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Simple channel validation - ensures URL
 * is valid, XML document is returned, and
 * document has an rss root element with a 
 * version, or rdf root element, /*w  w w  .jav  a2 s  .c  o m*/
 */
public static boolean isValid(URL url) throws HttpUserException {
    boolean valid = false;
    try {
        //         System.setProperty("networkaddress.cache.ttl", "0");

        HttpClient client = new HttpClient();
        ChannelManager.getChannelManager().configureHttpClient(client);
        if (url.getUserInfo() != null) {
            client.getState().setCredentials(null, null,
                    new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
        }

        String urlString = url.toString();
        HttpMethod method = null;

        int count = 0;
        HttpResult result = null;
        int statusCode = HttpStatus.SC_OK;
        boolean redirected = false;
        do {
            method = new GetMethod(urlString);
            method.setRequestHeader("User-agent", AppConstants.getUserAgent());
            method.setRequestHeader("Accept-Encoding", "gzip");
            method.setFollowRedirects(false);
            method.setDoAuthentication(true);

            HostConfiguration hostConfiguration = client.getHostConfiguration();
            URI hostURI = new URI(urlString);
            hostConfiguration.setHost(hostURI);

            result = executeHttpRequest(client, hostConfiguration, method);
            statusCode = result.getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statusCode == HttpStatus.SC_SEE_OTHER
                    || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirected = true;
                // Resolve against current URI - may be a relative URI
                try {
                    urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                } catch (URISyntaxException use) {
                    // Fall back to just using location from result
                    urlString = result.getLocation();
                }
            } else {
                redirected = false;
            }

            //            method.getResponseBody();
            //            method.releaseConnection();
            count++;
        } while (count < 5 && redirected);

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (statusCode == HttpStatus.SC_OK) {
            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);

            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();
            Document rssDoc = db.parse(bis);
            Element rootElm = rssDoc.getDocumentElement();

            for (int i = 0; i < parsers.length; i++) {
                if (parsers[i].isParsable(rootElm)) {
                    valid = true;
                    break;
                }
            }
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            throw new HttpUserException(statusCode);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new HttpUserException(statusCode);
        }

    } catch (URIException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valid;
}

From source file:org.mule.module.spring.security.AuthenticationAgainstMultipleProvidersTestCase.java

License:asdf

@Test
public void testProvider1() throws Exception {
    HttpClient httpClient = new HttpClient();
    Credentials credentials = new UsernamePasswordCredentials("admin1", "admin1");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setAuthenticationPreemptive(true);

    PostMethod postMethod = new PostMethod("http://localhost:4445");
    postMethod.setDoAuthentication(true);
    postMethod.setRequestEntity(new StringRequestEntity("hello", "text/html", "UTF-8"));

    assertEquals(HttpStatus.SC_OK, httpClient.executeMethod(postMethod));
    assertEquals("hello", postMethod.getResponseBodyAsString());

    credentials = new UsernamePasswordCredentials("asdf", "asdf");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, httpClient.executeMethod(postMethod));

    credentials = new UsernamePasswordCredentials("admin2", "admin2");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, httpClient.executeMethod(postMethod));
}

From source file:org.mule.module.spring.security.AuthenticationAgainstMultipleProvidersTestCase.java

License:asdf

@Test
public void testProvider2() throws Exception {
    HttpClient httpClient = new HttpClient();
    Credentials credentials = new UsernamePasswordCredentials("admin2", "admin2");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setAuthenticationPreemptive(true);

    PostMethod postMethod = new PostMethod("http://localhost:4446");
    postMethod.setDoAuthentication(true);
    postMethod.setRequestEntity(new StringRequestEntity("hello", "text/html", "UTF-8"));

    assertEquals(HttpStatus.SC_OK, httpClient.executeMethod(postMethod));
    assertEquals("hello", postMethod.getResponseBodyAsString());

    credentials = new UsernamePasswordCredentials("asdf", "asdf");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, httpClient.executeMethod(postMethod));

    credentials = new UsernamePasswordCredentials("admin", "admin");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, httpClient.executeMethod(postMethod));
}