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:com.cyberway.issue.crawler.frontier.AbstractFrontier.java

/**
 * Checks if a recently completed CrawlURI that did not finish successfully
 * needs to be retried (processed again after some time elapses)
 * /*from  w w w  .  ja  va 2  s . co  m*/
 * @param curi
 *            The CrawlURI to check
 * @return True if we need to retry.
 */
protected boolean needsRetrying(CrawlURI curi) {
    if (overMaxRetries(curi)) {
        return false;
    }

    switch (curi.getFetchStatus()) {
    case HttpStatus.SC_UNAUTHORIZED:
        // We can get here though usually a positive status code is
        // a success. We get here if there is rfc2617 credential data
        // loaded and we're supposed to go around again. See if any
        // rfc2617 credential present and if there, assume it got
        // loaded in FetchHTTP on expectation that we're to go around
        // again. If no rfc2617 loaded, we should not be here.
        boolean loaded = curi.hasRfc2617CredentialAvatar();
        if (!loaded && logger.isLoggable(Level.INFO)) {
            logger.info("Have 401 but no creds loaded " + curi);
        }
        return loaded;
    case S_DEFERRED:
    case S_CONNECT_FAILED:
    case S_CONNECT_LOST:
    case S_DOMAIN_UNRESOLVABLE:
        // these are all worth a retry
        // TODO: consider if any others (S_TIMEOUT in some cases?) deserve
        // retry
        return true;
    default:
        return false;
    }
}

From source file:com.thoughtworks.go.server.service.ValueStreamMapServiceTest.java

@Test
public void shouldPopulateErrorCorrectly_VSMForMaterial() throws Exception {
    /*/*ww w  .  j a  v a 2 s .c om*/
    git --> p1
     */

    String groupName = "g1";
    String pipelineName = "p1";
    String userName = "looser";
    GitMaterial gitMaterial = new GitMaterial("git");
    MaterialConfig gitConfig = gitMaterial.config();
    GitMaterialInstance gitMaterialInstance = new GitMaterialInstance("url", "branch", "submodule",
            "flyweight");
    PipelineConfigs groups = new BasicPipelineConfigs(groupName, new Authorization(),
            PipelineConfigMother.pipelineConfig(pipelineName, new MaterialConfigs(gitConfig)));
    CruiseConfig cruiseConfig = new BasicCruiseConfig(groups);
    when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
    when(goConfigService.groups()).thenReturn(new PipelineGroups(groups));

    when(securityService.hasViewPermissionForGroup(userName, groupName)).thenReturn(false);

    // unknown material
    valueStreamMapService.getValueStreamMap("unknown-material", "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_NOT_FOUND, "MATERIAL_CONFIG_WITH_FINGERPRINT_NOT_FOUND");

    // unauthorized
    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_UNAUTHORIZED, "MATERIAL_CANNOT_VIEW");

    // material config exists but no material instance
    when(securityService.hasViewPermissionForGroup(userName, groupName)).thenReturn(true);
    when(materialRepository.findMaterialInstance(gitConfig)).thenReturn(null);

    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_NOT_FOUND, "MATERIAL_INSTANCE_WITH_FINGERPRINT_NOT_FOUND");

    // modification (revision) doesn't exist
    when(materialRepository.findMaterialInstance(gitConfig)).thenReturn(gitMaterialInstance);
    when(materialRepository.findModificationWithRevision(gitMaterial, "r1")).thenReturn(null);

    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_NOT_FOUND, "MATERIAL_MODIFICATION_NOT_FOUND");

    // internal error
    when(goConfigService.groups()).thenThrow(new RuntimeException("just for fun"));

    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, "VSM_INTERNAL_SERVER_ERROR_FOR_MATERIAL");
}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Send 401 Unauthorized response./*from   w  w w  . ja  v  a 2s . co m*/
 *
 * @throws IOException on error
 */
public void sendUnauthorized() throws IOException {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("WWW-Authenticate", "Basic realm=\"" + BundleMessage.format("UI_DAVMAIL_GATEWAY") + '\"');
    sendHttpResponse(HttpStatus.SC_UNAUTHORIZED, headers, null, (byte[]) null, true);
}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Send Http response with given status, headers, content type and content.
 * Close connection if keepAlive is false
 *
 * @param status      Http status/*from   ww  w .  j a  v a  2 s  .  com*/
 * @param headers     Http headers
 * @param contentType MIME content type
 * @param content     response body as byte array
 * @param keepAlive   keep connection open
 * @throws IOException on error
 */
public void sendHttpResponse(int status, Map<String, String> headers, String contentType, byte[] content,
        boolean keepAlive) throws IOException {
    sendClient("HTTP/1.1 " + status + ' ' + HttpStatus.getStatusText(status));
    if (status != HttpStatus.SC_UNAUTHORIZED) {
        sendClient("Server: DavMail Gateway " + DavGateway.getCurrentVersion());
        sendClient("DAV: 1, calendar-access, calendar-schedule, calendarserver-private-events, addressbook");
        SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
        // force GMT timezone
        formatter.setTimeZone(ExchangeSession.GMT_TIMEZONE);
        String now = formatter.format(new Date());
        sendClient("Date: " + now);
        sendClient("Expires: " + now);
        sendClient("Cache-Control: private, max-age=0");
    }
    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            sendClient(header.getKey() + ": " + header.getValue());
        }
    }
    if (contentType != null) {
        sendClient("Content-Type: " + contentType);
    }
    closed = closed || !keepAlive;
    sendClient("Connection: " + (closed ? "close" : "keep-alive"));
    if (content != null && content.length > 0) {
        sendClient("Content-Length: " + content.length);
    } else if (headers == null || !"chunked".equals(headers.get("Transfer-Encoding"))) {
        sendClient("Content-Length: 0");
    }
    sendClient("");
    if (content != null && content.length > 0) {
        // full debug trace
        if (wireLogger.isDebugEnabled()) {
            wireLogger.debug("> " + new String(content, "UTF-8"));
        }
        sendClient(content);
    }
}

From source file:net.xmind.share.jobs.UploadJob.java

private IStatus promptError(int uploadStatus, IStatus error) {
    int code = error.getCode();
    String message = null;/*from www  .ja  v a2s.c  o m*/
    boolean tryAgainAllowed = true;
    if (uploadStatus == UploadSession.PREPARING) {
        if (code > 0) {
            if (code == HttpStatus.SC_UNAUTHORIZED) {
                resignin();
                return Status.CANCEL_STATUS;
            }
        }
    } else if (uploadStatus == UploadSession.UPLOADING) {
        if (code > 0) {
            if (code == HttpStatus.SC_NOT_FOUND) {
                return Status.CANCEL_STATUS;
            } else if (code == UploadSession.CODE_VERIFICATION_FAILURE) {
                message = Messages.ErrorDialog_Unauthorized_message;
                tryAgainAllowed = false;
            }
        }
    }

    if (message == null)
        message = Messages.ErrorDialog_message;

    promptErrorMessage(message, tryAgainAllowed);
    return error;
}

From source file:org.alfresco.dataprep.AlfrescoHttpClient.java

/**
 * Execute HttpClient request.//from w  w w .j ava 2  s .  c o  m
 * @param userName String user name 
 * @param password String password
 * @param request HttpRequestBase the request
 * @return {@link HttpResponse} response
 */
public HttpResponse executeRequest(final String userName, final String password, HttpRequestBase request) {
    HttpResponse response = null;
    client = getHttpClientWithBasicAuth(userName, password);
    try {
        response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new RuntimeException("Invalid user name or password");
        }
    } catch (IOException e) {
        logger.error(response);
        throw new RuntimeException("Error while executing request", e);
    } finally {
        request.releaseConnection();
        close();
    }
    return response;
}

From source file:org.alfresco.dataprep.AlfrescoHttpClient.java

/**
 * Execute HttpClient POST OR PUT/*from  www . j a va2  s .  c om*/
 * @param userName String user name 
 * @param password String password
 * @param body JSONObject body of the request
 * @param request HttpEntityEnclosingRequestBase the request
 * @return {@link HttpResponse} response
 */
public HttpResponse executeRequest(final String userName, final String password, final JSONObject body,
        HttpEntityEnclosingRequestBase request) {
    HttpResponse response = null;
    client = getHttpClientWithBasicAuth(userName, password);
    request.setEntity(setMessageBody(body));
    try {
        response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new RuntimeException("Invalid user name or password");
        }
    } catch (IOException e) {
        logger.error(response);
        throw new RuntimeException("Error while executing request", e);
    } finally {
        request.releaseConnection();
        close();
    }
    return response;
}

From source file:org.alfresco.dataprep.DataListsService.java

@SuppressWarnings("unchecked")
private List<String> getDataListIds(final String userName, final String password, final String siteName,
        final String dataListTitle) {
    List<String> ids = new ArrayList<String>();
    HttpResponse response = getDataLists(userName, password, siteName);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
        String strResponse = "";
        Object obj = null;//w  w w . j ava 2 s.  c o m
        try {
            strResponse = EntityUtils.toString(response.getEntity());
            JSONParser parser = new JSONParser();
            obj = parser.parse(strResponse);
        } catch (ParseException | IOException e) {
            throw new RuntimeException("Failed to parse the response: " + strResponse);
        }
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray jArray = (JSONArray) jsonObject.get("datalists");
        Iterator<JSONObject> iterator = ((List<JSONObject>) jArray).iterator();
        while (iterator.hasNext()) {
            JSONObject factObj = (JSONObject) iterator.next();
            String theTitle = (String) factObj.get("title");
            if (dataListTitle.toString().equalsIgnoreCase(theTitle)) {
                ids.add((String) factObj.get("nodeRef"));
                ids.add((String) factObj.get("name"));
            }
        }
        return ids;
    case HttpStatus.SC_NOT_FOUND:
        throw new RuntimeException("Invalid site " + siteName);
    case HttpStatus.SC_UNAUTHORIZED:
        throw new RuntimeException("Invalid credentials");
    default:
        logger.error("Unable to find: " + dataListTitle + " " + response.toString());
        break;
    }
    return ids;
}

From source file:org.alfresco.dataprep.SitePagesService.java

/**
 * Get the name (ID) of the event//  w  w w.j  av a  2  s .  c  om
 * @param userName String user name
 * @param password String user password
 * @param siteName String site name
 * @param what String what
 * @param where String event location
 * @param from Date event start date
 * @param to Date event end date
 * @param timeStart String event start time
 * @param timeEnd String event time finish
 * @param allDay boolean all day event
 * @return String name (id) of event
 */
public String getEventName(final String userName, final String password, final String siteName,
        final String what, final String where, Date from, Date to, String timeStart, String timeEnd,
        final boolean allDay) {
    String name = "";
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    to = calendar.getTime();
    String strFrom = dateFormat.format(from);
    String strTo = dateFormat.format(to);
    String reqURL = client.getAlfrescoUrl() + "alfresco/s/calendar/events/" + siteName + "/user?from=" + strFrom
            + "&to" + strTo + "&repeating=all";
    HttpGet get = new HttpGet(reqURL);
    try {
        HttpResponse response = client.execute(userName, password, get);
        switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
            org.json.JSONObject items = new org.json.JSONObject(EntityUtils.toString(response.getEntity()));
            org.json.JSONArray events = items.getJSONArray("events");
            for (int i = 0; i < events.length(); i++) {
                String itemWhat = items.getJSONArray("events").getJSONObject(i).getString("title");
                String itemWhere = items.getJSONArray("events").getJSONObject(i).getString("where");
                if (allDay) {
                    if (itemWhat.equals(what) || itemWhere.equals(where)) {
                        name = items.getJSONArray("events").getJSONObject(i).getString("name");
                    }
                } else {
                    String sTime = events.getJSONObject(i).getJSONObject("startAt").getString("iso8601");
                    String eTime = events.getJSONObject(i).getJSONObject("endAt").getString("iso8601");
                    DateTime st = new DateTime(sTime);
                    DateTime et = new DateTime(eTime);
                    DateTimeFormatter sdf = DateTimeFormat.forPattern("HH:mm");
                    sTime = st.toString(sdf);
                    eTime = et.toString(sdf);
                    if (timeStart.contains("AM") || timeStart.contains("PM")) {
                        timeStart = convertTo24Hour(timeStart);
                    }
                    if (timeEnd.contains("AM") || timeEnd.contains("PM")) {
                        timeEnd = convertTo24Hour(timeEnd);
                    }
                    if (itemWhat.equals(what) && sTime.equals(timeStart) && eTime.equals(timeEnd)) {
                        name = items.getJSONArray("events").getJSONObject(i).getString("name");
                        break;
                    }
                }
            }
            return name;
        case HttpStatus.SC_UNAUTHORIZED:
            throw new RuntimeException("Invalid credentials");
        default:
            logger.error("Unable to find event " + response.toString());
            break;
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to execute request:" + get, e);
    } finally {
        get.releaseConnection();
        client.close();
    }
    return name;
}

From source file:org.alfresco.dataprep.SitePagesService.java

/**
 * Get the name (id) for blog post, link, discussion
 * @param userName String user name/*from   w w  w.  j  av a  2 s.c o m*/
 * @param password String password
 * @param siteName String site name
 * @param title String blog title
 * @param draftBlog boolean is blog draft
 * @return Map<String, String> name, nodeRef and replyUrl
 * @throws RuntimeException if site is not found
 */
@SuppressWarnings("unchecked")
private Map<String, String> getIds(final String userName, final String password, final String siteName,
        final String title, final Page page) {
    String url = "";
    Map<String, String> ids = new HashMap<String, String>();
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    switch (page) {
    case LINKS:
        url = client.getApiUrl() + "links/site/" + siteName
                + "/links?filter=all&contentLength=512&page=1&pageSize=10&startIndex=0";
        break;
    case BLOG:
        url = client.getApiUrl() + "blog/site/" + siteName + "/blog/posts";
        break;
    case DISCUSSIONS:
        url = client.getApiUrl() + "forum/site/" + siteName + "/discussions/posts";
        break;
    default:
        break;
    }
    HttpGet get = new HttpGet(url);
    try {
        HttpResponse response = client.execute(userName, password, get);
        switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
            JSONArray jArray = client.getJSONArray(response, "", "items");
            Iterator<JSONObject> iterator = ((List<JSONObject>) jArray).iterator();
            while (iterator.hasNext() && jArray.size() > 0) {
                JSONObject factObj = (JSONObject) iterator.next();
                String theTitle = (String) factObj.get("title");
                if (title.toString().equalsIgnoreCase(theTitle)) {
                    ids.put("name", (String) factObj.get("name"));
                    ids.put("nodeRef", (String) factObj.get("nodeRef"));
                    if (page.pageId.equals("discussions-topiclist")) {
                        ids.put("repliesUrl", (String) factObj.get("repliesUrl"));
                    } else if (page.pageId.equals("blog-postlist") || page.pageId.equals("links")) {
                        ids.put("commentsUrl", (String) factObj.get("commentsUrl"));
                    }
                    return ids;
                }
            }
            return ids;
        case HttpStatus.SC_NOT_FOUND:
            throw new RuntimeException("Invalid site " + siteName);
        case HttpStatus.SC_UNAUTHORIZED:
            throw new RuntimeException("Invalid credentials");
        default:
            logger.error("Unable to find: " + title + " " + response.toString());
            break;
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to execute request:" + get, e);
    } finally {
        get.releaseConnection();
        client.close();
    }
    return ids;
}