Java 类javax.security.auth.login.CredentialNotFoundException 实例源码

项目:azure-keyvault-plugin    文件:AzureKeyVaultBuildWrapper.java   
public AzureKeyVaultCredential getKeyVaultCredential(Run<?, ?> build) throws CredentialNotFoundException, CredentialException
{
    // Try override values
    LOGGER.log(Level.INFO, String.format("Trying override credentials..."));
    AzureKeyVaultCredential credential = getKeyVaultCredential(build, this.applicationSecret, this.credentialID);
    if (credential.isValid())
    {
        LOGGER.log(Level.INFO, String.format("Using override credentials"));
        return credential;
    }

    // Try global values
    LOGGER.log(Level.INFO, String.format("Trying global credentials"));
    credential = getKeyVaultCredential(build, getDescriptor().getApplicationSecret(), getDescriptor().getCredentialID());
    if (credential.isValid())
    {
        LOGGER.log(Level.INFO, String.format("Using global credentials"));
        return credential;
    }
    throw new CredentialNotFoundException("Unable to find a valid credential with provided parameters");
}
项目:azure-keyvault-plugin    文件:AzureKeyVaultBuildWrapper.java   
public AzureKeyVaultCredential getKeyVaultCredential(Run<?, ?> build, Secret _applicationSecret, String _credentialID) 
    throws CredentialNotFoundException, CredentialException
{
    // Try Credential
    if (!AzureKeyVaultUtil.isNullOrEmpty(_credentialID))
    {
        LOGGER.log(Level.INFO, String.format("Fetching credentials by ID"));
        AzureKeyVaultCredential credential = getCredentialById(_credentialID, build);
        if (!credential.isApplicationIDValid())
        {
            LOGGER.log(Level.INFO, String.format("Credential is password-only. Setting the username"));
            // Credential only contains the app secret - add the app id
            credential.setApplicationID(getApplicationID());
        }
        return credential;
    }

    // Try AppID/Secret
    if (!AzureKeyVaultUtil.isNullOrEmpty(_applicationSecret))
    {
        LOGGER.log(Level.WARNING, String.format("Using explicit application secret. This will be deprecated in 1.0. Use Credential ID instead."));
        return new AzureKeyVaultCredential(getApplicationID(), _applicationSecret);
    }

    return new AzureKeyVaultCredential();
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Gets the text of a deleted page (it's like getPageText, but for deleted
 *  pages).
 *  @param page a page
 *  @return the deleted text, or null if there is no deleted text to retrieve
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if we cannot obtain deleted revisions
 *  @since 0.30
 */
public String getDeletedText(String page) throws IOException, CredentialNotFoundException
{
    if (user == null || !user.isAllowedTo("deletedhistory") || !user.isAllowedTo("deletedtext"))
        throw new CredentialNotFoundException("Permission denied: not able to view deleted history or text.");

    // TODO: this can be multiquery(?)
    StringBuilder url = new StringBuilder(query);
    url.append("prop=deletedrevisions&drvlimit=1&drvprop=content&titles=");
    url.append(encode(page, true));

    // expected form: <rev timestamp="2009-04-05T22:40:35Z" xml:space="preserve">TEXT OF PAGE</rev>
    String line = fetch(url.toString(), "getDeletedText");
    int a = line.indexOf("<rev ");
    if (a < 0)
        return null;
    a = line.indexOf(">", a) + 1;
    int b = line.indexOf("</rev>", a);
    log(Level.INFO, "getDeletedText", "Successfully retrieved deleted text of page " + page);
    return line.substring(a, b);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Internal method for interfacing with the watchlist, since the API URLs
 *  for (un)watching are very similar.
 *
 *  @param titles the titles to (un)watch
 *  @param unwatch whether we should unwatch these pages
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if not logged in
 *  @see #watch
 *  @see #unwatch
 *  @since 0.18
 */
protected void watchInternal(boolean unwatch, String... titles) throws IOException, CredentialNotFoundException
{
    // create the watchlist cache
    String state = unwatch ? "unwatch" : "watch";
    if (watchlist == null)
        getRawWatchlist();
    for (String titlestring : constructTitleString(titles))
    {
        StringBuilder request = new StringBuilder("titles=");
        request.append(titlestring);
        if (unwatch)
            request.append("&unwatch=1");
        request.append("&token=");
        request.append(getToken("watch"));

        post(apiUrl + "action=watch", request.toString(), state);
    }
    log(Level.INFO, state, "Successfully " + state + "ed " + Arrays.toString(titles));
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Fetches data from one of a set of miscellaneous special pages.
 *  WARNING: some of these may be *CACHED*, *DISABLED* and/or *LIMITED* on
 *  large wikis.
 *
 *  @param page one of { Ancientpages, BrokenRedirects, Deadendpages,
 *  Disambiguations, DoubleRedirects, Listredirects, Lonelypages, Longpages,
 *  Mostcategories, Mostimages, Mostinterwikis, Mostlinkedcategories,
 *  Mostlinkedtemplates, Mostlinked, Mostrevisions, Fewestrevisions, Shortpages,
 *  Uncategorizedcategories, Uncategorizedpages, Uncategorizedimages,
 *  Uncategorizedtemplates, Unusedcategories, Unusedimages, Wantedcategories,
 *  Wantedfiles, Wantedpages, Wantedtemplates, Unwatchedpages, Unusedtemplates,
 *  Withoutinterwiki }. This parameter is *case sensitive*.
 *  @return the list of pages returned by that particular special page
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if page=Unwatchedpages and we cannot
 *  read it
 *  @since 0.28
 */
public String[] queryPage(String page) throws IOException, CredentialNotFoundException
{
    if (page.equals("Unwatchedpages") && (user == null || !user.isAllowedTo("unwatchedpages")))
        throw new CredentialNotFoundException("User does not have the \"unwatchedpages\" permission.");

    String url = query + "action=query&list=querypage&qplimit=max&qppage=" + page + "&qpcontinue=";
    String offset = "";
    List<String> pages = new ArrayList<>(1333);

    do
    {
        String line = fetch(url + offset, "queryPage");
        offset = parseAttribute(line, "qpoffset", 0);

        // xml form: <page value="0" ns="0" title="Anorthosis Famagusta FC in European football" />
        for (int x = line.indexOf("<page "); x > 0; x = line.indexOf("<page ", ++x))
            pages.add(parseAttribute(line, "title", x));
    }
    while (offset != null);
    int temp = pages.size();
    log(Level.INFO, "queryPage", "Successfully retrieved [[Special:" + page + "]] (" + temp + " pages)");
    return pages.toArray(new String[temp]);
}
项目:wiki-java    文件:ContributionSurveyor.java   
/**
 *  Performs a survey of a user's deleted contributions. Requires 
 *  administrator access to the relevant wiki. (Note: due to MediaWiki
 *  limitations, it is not possible to filter by bytes added or whether an
 *  edit created a new page.)
 * 
 *  @param username the user to survey
 *  @param ns the namespaces to survey (not specified = all namespaces)
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if one cannot view deleted pages
 *  @since 0.03
 */
public LinkedHashMap<String, ArrayList<Wiki.Revision>> deletedContributionSurvey(String username, 
    int... ns) throws IOException, CredentialNotFoundException
{
    // this looks a lot like ArticleEditorIntersector.intersectEditors()...
    Wiki.Revision[] delcontribs = wiki.deletedContribs(username, null, 
        null, false, ns);
    LinkedHashMap<String, ArrayList<Wiki.Revision>> ret = new LinkedHashMap<>();

    // group contributions by page
    for (Wiki.Revision rev : delcontribs)
    {
        String page = rev.getPage();
        if (!ret.containsKey(page))
            ret.put(page, new ArrayList<Wiki.Revision>());
        ret.get(page).add(rev);
    }
    return ret;
}
项目:awseb-deployment-plugin    文件:AWSClientFactory.java   
public static AmazonWebServicesCredentials lookupNamedCredential(String credentialsId)
    throws CredentialNotFoundException {
  List<AmazonWebServicesCredentials> credentialList =
      CredentialsProvider.lookupCredentials(
          AmazonWebServicesCredentials.class, Jenkins.getInstance(), ACL.SYSTEM,
          Collections.<DomainRequirement>emptyList());

  AmazonWebServicesCredentials cred =
      CredentialsMatchers.firstOrNull(credentialList,
                                      CredentialsMatchers.allOf(
                                          CredentialsMatchers.withId(credentialsId)));

  if (cred == null) {
    throw new CredentialNotFoundException(credentialsId);
  }
  return cred;
}
项目:cas-5.1.0    文件:SurrogateAuthenticationAspect.java   
/**
 * Handle surrogate principal creation post authentication.
 *
 * @param jp         the jp
 * @param credential the credential
 * @return the object
 * @throws Throwable the throwable
 */
@Around(value = "execution(public org.apereo.cas.authentication.HandlerResult "
        + "org.apereo.cas.authentication.AuthenticationHandler.authenticate(..)) "
        + "&& args(credential)")
public Object handleSurrogate(final ProceedingJoinPoint jp, final Credential credential) throws Throwable {
    try {
        if (!credential.getClass().equals(SurrogateUsernamePasswordCredential.class)) {
            return jp.proceed();
        }
        final SurrogateUsernamePasswordCredential surrogateCredentials = (SurrogateUsernamePasswordCredential) credential;
        final String targetUserId = surrogateCredentials.getSurrogateUsername();
        if (StringUtils.isBlank(targetUserId)) {
            LOGGER.error("No surrogate username was specified as part of the credential");
            throw new CredentialNotFoundException("Missing surrogate username in credential");
        }
        final HandlerResult result = (HandlerResult) jp.proceed();
        LOGGER.debug("Authenticated [{}] will be checked for surrogate eligibility next...", result.getPrincipal());

        if (this.surrogateAuthenticationService.canAuthenticateAs(targetUserId, result.getPrincipal())) {
            final Principal principal = this.principalFactory.createPrincipal(targetUserId);
            final AuthenticationHandler handler = AuthenticationHandler.class.cast(jp.getTarget());
            return new DefaultHandlerResult(handler, new BasicCredentialMetaData(credential), principal);
        }
        LOGGER.error("Principal [{}] is unable/unauthorized to authenticate as [{}]", result.getPrincipal(), targetUserId);
        throw new FailedLoginException();
    } catch (final Throwable e) {
        throw e;
    }
}
项目:azure-keyvault-plugin    文件:AzureKeyVaultBuildWrapper.java   
public AzureKeyVaultCredential getCredentialById(String _credentialID, Run<?, ?> build) throws CredentialNotFoundException, CredentialException
{
    AzureKeyVaultCredential credential = new AzureKeyVaultCredential();
    IdCredentials cred = CredentialsProvider.findCredentialById(_credentialID, IdCredentials.class, build);

    if (cred==null)
    {
        throw new CredentialNotFoundException(_credentialID);
    }

    if(StringCredentials.class.isInstance(cred))
    {
        // Secret Text object
        LOGGER.log(Level.INFO, String.format("Fetched %s as StringCredentials", _credentialID));
        CredentialsProvider.track(build, cred);
        credential.setApplicationSecret(StringCredentials.class.cast(cred).getSecret());
        return credential;
    }
    else if(StandardUsernamePasswordCredentials.class.isInstance(cred))
    {
        // Username/Password Object
        LOGGER.log(Level.INFO, String.format("Fetched %s as StandardUsernamePasswordCredentials", _credentialID));
        CredentialsProvider.track(build, cred);
        credential.setApplicationID(StandardUsernamePasswordCredentials.class.cast(cred).getUsername());
        credential.setApplicationSecret(StandardUsernamePasswordCredentials.class.cast(cred).getPassword());
        return credential;
    }
    else
    {
        throw new CredentialException("Could not determine the type for Secret id " + _credentialID + " only 'Secret Text' and 'Username/Password' are supported");
    }
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Returns all deleted pages that begin with the given prefix. WARNING:
 *  this does not behave like [[Special:Prefixindex]]. See [[Special:Undelete]]
 *  with no arguments.
 *
 *  @param prefix a prefix without a namespace specifier, empty string
 *  lists all deleted pages in the namespace.
 *  @param namespace one (and only one) namespace -- not ALL_NAMESPACES
 *  @return (see above)
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if we cannot view deleted pages
 *  @throws IllegalArgumentException if namespace == ALL_NAMESPACES
 *  @since 0.31
 */
public String[] deletedPrefixIndex(String prefix, int namespace) throws IOException, CredentialNotFoundException
{
    if (user == null || !user.isAllowedTo("deletedhistory") || !user.isAllowedTo("deletedtext"))
        throw new CredentialNotFoundException("Permission denied: not able to view deleted history or text.");

    // disallow ALL_NAMESPACES, this query is extremely slow and likely to error out.
    if (namespace == ALL_NAMESPACES)
        throw new IllegalArgumentException("deletedPrefixIndex: you must choose a namespace.");

    StringBuilder url = new StringBuilder(query);
    url.append("generator=alldeletedrevisions&gadrdir=newer&gadrgeneratetitles=1&gadrprefix=");
    url.append(encode(prefix, false));
    url.append("&gadrlimit=max&gadrnamespace=");
    url.append(namespace);

    String drcontinue = null;
    List<String> pages = new ArrayList<>();
    do
    {
        String text;
        if (drcontinue == null)
            text = fetch(url.toString(), "deletedPrefixIndex");
        else
            text = fetch(url.toString() + "&gadrcontinue=" + encode(drcontinue, false), "deletedPrefixIndex");
        drcontinue = parseAttribute(text, "gadrcontinue", 0);

        for (int x = text.indexOf("<page ", 0); x > 0; x = text.indexOf("<page ", ++x))
            pages.add(parseAttribute(text, "title", x));
    }
    while (drcontinue != null);
    int size = pages.size();
    log(Level.INFO, "deletedPrefixIndex", "Successfully retrieved deleted page list (" + size + " items).");
    return pages.toArray(new String[size]);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Sends an email message to a user in a similar manner to [[Special:Emailuser]].
 *  You and the target user must have a confirmed email address and the
 *  target user must have email contact enabled. Messages are sent in plain
 *  text (no wiki markup or HTML).
 *
 *  @param user a Wikipedia user with email enabled
 *  @param subject the subject of the message
 *  @param message the plain text message
 *  @param emailme whether to send a copy of the message to your email address
 *  @throws IOException if a network error occurs
 *  @throws CredentialExpiredException if cookies have expired
 *  @throws AccountLockedException if you have been blocked from sending email
 *  @throws UnsupportedOperationException if email is disabled or if you do
 *  not have a verified email address
 *  @since 0.24
 */
public synchronized void emailUser(User user, String message, String subject, boolean emailme) throws IOException, LoginException
{
    throttle();

    // check if blocked, logged in
    if (this.user == null || !this.user.isAllowedTo("sendemail"))
        throw new CredentialNotFoundException("Permission denied: cannot email.");

    // is this user emailable?
    if (!(Boolean)user.getUserInfo().get("emailable"))
    {
        // should throw an exception here
        log(Level.WARNING, "emailUser", "User " + user.getUsername() + " is not emailable");
        return;
    }

    // post email
    StringBuilder buffer = new StringBuilder(20000);
    buffer.append("token=");
    buffer.append(encode(getToken("csrf"), false));
    buffer.append("&target=");
    buffer.append(encode(user.getUsername(), false));
    if (emailme)
        buffer.append("&ccme=true");
    buffer.append("&text=");
    buffer.append(encode(message, false));
    buffer.append("&subject=");
    buffer.append(encode(subject, false));
    String response = post(apiUrl + "action=emailuser", buffer.toString(), "emailUser");

    // check for errors
    checkErrorsAndUpdateStatus(response, "email");
    if (response.contains("error code=\"cantsend\""))
        throw new UnsupportedOperationException("Email is disabled for this wiki or you do not have a confirmed email address.");
    log(Level.INFO, "emailUser", "Successfully emailed " + user.getUsername() + ".");
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Fetches recent changes to pages on your watchlist. Data is retrieved
 *  from the <tt>recentchanges</tt> table and hence cannot be older than
 *  about a month.
 *
 *  @param allrev show all revisions to the pages, instead of the top most
 *  change
 *  @param ns a list of namespaces to filter by, empty = all namespaces.
 *  @return list of changes to watched pages and their talk pages
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if not logged in
 *  @since 0.27
 */
public Revision[] watchlist(boolean allrev, int... ns) throws IOException, CredentialNotFoundException
{
    if (user == null)
        throw new CredentialNotFoundException("Not logged in");
    StringBuilder url = new StringBuilder(query);
    url.append("list=watchlist&wlprop=ids%7Ctitle%7Ctimestamp%7Cuser%7Ccomment%7Csizes&wllimit=max");
    if (allrev)
        url.append("&wlallrev=true");
    constructNamespaceString(url, "wl", ns);

    List<Revision> wl = new ArrayList<>(667);
    String wlstart = "";
    do
    {
        String line = fetch(url.toString() + "&wlstart=" + wlstart, "watchlist");
        wlstart = parseAttribute(line, "wlstart", 0);

        // xml form: <item pageid="16396" revid="176417" ns="0" title="API:Query - Lists" />
        for (int i = line.indexOf("<item "); i > 0; i = line.indexOf("<item ", ++i))
        {
            int j = line.indexOf("/>", i);
            wl.add(parseRevision(line.substring(i, j), ""));
        }
    }
    while (wlstart != null);
    int size = wl.size();
    log(Level.INFO, "watchlist", "Successfully retrieved watchlist (" + size + " items)");
    return wl.toArray(new Revision[size]);
}
项目:cn1    文件:CredentialNotFoundExceptionTest.java   
/**
 * @tests javax.security.auth.login.CredentialNotFoundException#CredentialNotFoundException(
 *        java.lang.String)
 */
public final void testCtor2() {
    assertNull(new CredentialNotFoundException(null).getMessage());

    String message = "";
    assertSame(message, new CredentialNotFoundException(message)
            .getMessage());

    message = "message";
    assertSame(message, new CredentialNotFoundException(message)
            .getMessage());
}
项目:module.jaxrs-filter-security    文件:HashedCredentialsMatcher.java   
@Override
public boolean matches(Account account, AuthenticationToken token) throws CredentialException {
    Object tokenCredentials = token.readCredentials();
    if (tokenCredentials == null) {
        throw new CredentialNotFoundException("token");
    }
    Object accountCredentials = account.getCredentials();
    if (accountCredentials == null) {
        throw new CredentialNotFoundException("account");
    }
    String hashed = Crypto.sha512(tokenCredentials.toString(), account.getPrincipal().getName(), hashIterations);
    return accountCredentials.toString().equals(hashed);
}
项目:freeVM    文件:CredentialNotFoundExceptionTest.java   
/**
 * @tests javax.security.auth.login.CredentialNotFoundException#CredentialNotFoundException(
 *        java.lang.String)
 */
public final void testCtor2() {
    assertNull(new CredentialNotFoundException(null).getMessage());

    String message = "";
    assertSame(message, new CredentialNotFoundException(message)
            .getMessage());

    message = "message";
    assertSame(message, new CredentialNotFoundException(message)
            .getMessage());
}
项目:freeVM    文件:CredentialNotFoundExceptionTest.java   
/**
 * @tests javax.security.auth.login.CredentialNotFoundException#CredentialNotFoundException(
 *        java.lang.String)
 */
public final void testCtor2() {
    assertNull(new CredentialNotFoundException(null).getMessage());

    String message = "";
    assertSame(message, new CredentialNotFoundException(message)
            .getMessage());

    message = "message";
    assertSame(message, new CredentialNotFoundException(message)
            .getMessage());
}
项目:tomee    文件:TomcatSecurityService.java   
public UUID login(final String realmName, final String username, final String password) throws LoginException {
    final Realm realm = findRealm(realmName);
    if (realm == null) {
        throw new LoginException("No Tomcat realm available");
    }

    final Principal principal = realm.authenticate(username, password);
    if (principal == null) {
        throw new CredentialNotFoundException(username);
    }

    final Subject subject = createSubject(realm, principal);
    return registerSubject(subject);
}
项目:awseb-deployment-plugin    文件:AWSClientFactory.java   
public static AWSClientFactory getClientFactory(String credentialsId, String awsRegion)
    throws CredentialNotFoundException {
  AmazonWebServicesCredentials cred = null;

  if (isNotBlank(credentialsId)) {
    cred = lookupNamedCredential(credentialsId);
  }

  return getClientFactory(cred, awsRegion);
}
项目:fcrepo3-security-jaas    文件:DrupalMultisiteAuthModule.java   
@Override
public boolean login() throws LoginException {
    if (debug) {
        logger.debug(String.format("%s login called.", DrupalMultisiteAuthModule.class.getName()));
        for (String key : sharedState.keySet()) {
            String value = sharedState.get(key).toString();
            logger.debug(key + ": " + value);
        }
    }

    String[] keys = config.keySet().toArray(new String[0]);
    NameCallback nc = new NameCallback("username");
    PasswordCallback pc = new PasswordCallback("password", false);
    KeyChoiceCallback kcc = new KeyChoiceCallback(keys);
    Callback[] callbacks = new Callback[] {
            nc, pc, kcc
    };

    try {
        handler.handle(callbacks);
        username = nc.getName();
        char[] passwordCharArray = pc.getPassword();
        String password = new String(passwordCharArray);
        int[] key_selections = kcc.getSelectedIndexes();

        // Should only be exactly one item in key_selections; however,
        // let's iterate for brevity.
        for (int i : key_selections) {
            findUser(username, password, keys[i]);
        }

    }
    catch (IOException ioe) {
        ioe.printStackTrace();
        throw new LoginException("IOException occured: " + ioe.getMessage());
    }
    catch (MissingCredsException mce) {
        throw new CredentialNotFoundException(
                String.format("Missing \"key\", required for module %s.", this.getClass().getName()));
    }
    catch (UnsupportedCallbackException ucbe) {
        throw new LoginException("UnsupportedCallbackException: " + ucbe.getMessage());
    }

    return successLogin;
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Deletes a page. Does not delete any page requiring <tt>bigdelete</tt>.
 *  @param title the page to delete
 *  @param reason the reason for deletion
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if the user lacks the permission to
 *  delete
 *  @throws CredentialExpiredException if cookies have expired
 *  @throws AccountLockedException if user is blocked
 *  @since 0.24
 */
public synchronized void delete(String title, String reason) throws IOException, LoginException
{
    throttle();
    if (user == null || !user.isAllowedTo("delete"))
        throw new CredentialNotFoundException("Cannot delete: Permission denied");

    // edit token
    Map info = getPageInfo(title);
    if (!(Boolean)info.get("exists"))
    {
        log(Level.INFO, "delete", "Page \"" + title + "\" does not exist.");
        return;
    }
    String deleteToken = (String)info.get("token");

    // post data
    StringBuilder buffer = new StringBuilder(500);
    buffer.append("title=");
    buffer.append(encode(title, true));
    buffer.append("&reason=");
    buffer.append(encode(reason, false));
    buffer.append("&token=");
    buffer.append(encode(deleteToken, false));
    String response = post(apiUrl + "action=delete", buffer.toString(), "delete");

    // done
    try
    {
        if (!response.contains("<delete title="))
            checkErrorsAndUpdateStatus(response, "delete");
    }
    catch (IOException e)
    {
        // retry once
        if (retry)
        {
            retry = false;
            log(Level.WARNING, "delete", "Exception: " + e.getMessage() + " Retrying...");
            delete(title, reason);
        }
        else
        {
            log(Level.SEVERE, "delete", "EXCEPTION: " + e);
            throw e;
        }
    }
    if (retry)
        log(Level.INFO, "delete", "Successfully deleted " + title);
    retry = true;
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Undeletes a page. Equivalent to [[Special:Undelete]]. Restores ALL deleted
 *  revisions and files by default. This method is throttled.
 *  @param title a page to undelete
 *  @param reason the reason for undeletion
 *  @param revisions a list of revisions for selective undeletion
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if we cannot undelete
 *  @throws CredentialExpiredException if cookies have expired
 *  @throws AccountLockedException if user is blocked
 *  @since 0.30
 */
public synchronized void undelete(String title, String reason, Revision... revisions) throws IOException, LoginException
{
    throttle();
    if (user == null || !user.isAllowedTo("undelete"))
        throw new CredentialNotFoundException("Cannot undelete: Permission denied");

    StringBuilder out = new StringBuilder("title=");
    out.append(encode(title, true));
    out.append("&reason=");
    out.append(encode(reason, false));
    out.append("&token=");
    out.append(encode(getToken("csrf"), false));
    if (revisions.length != 0)
    {
        out.append("&timestamps=");
        for (int i = 0; i < revisions.length - 1; i++)
        {
            out.append(calendarToTimestamp(revisions[i].getTimestamp()));
            out.append("%7C");
        }
        out.append(calendarToTimestamp(revisions[revisions.length - 1].getTimestamp()));
    }
    String response = post(apiUrl + "action=undelete", out.toString(), "undelete");

    // done
    try
    {
        if (!response.contains("<undelete title="))
        {
            checkErrorsAndUpdateStatus(response, "undelete");
            if (response.contains("cantundelete"))
                log(Level.WARNING, "undelete", "Can't undelete: " + title + " has no deleted revisions.");
        }            
    }
    catch (IOException e)
    {
        // retry once
        if (retry)
        {
            retry = false;
            log(Level.WARNING, "undelete", "Exception: " + e.getMessage() + " Retrying...");
            undelete(title, reason, revisions);
        }
        else
        {
            log(Level.SEVERE, "undelete", "EXCEPTION: " + e);
            throw e;
        }
    }
    if (retry)
        log(Level.INFO, "undelete", "Successfully undeleted " + title);
    retry = true;
    for (Revision rev : revisions)
        rev.pageDeleted = false;
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Gets the deleted history of a page.
 *  @param title a page
 *  @param start the EARLIEST of the two dates
 *  @param end the LATEST of the two dates
 *  @param reverse whether to put the oldest first (default = false, newest
 *  first is how history pages work)
 *  @return the deleted revisions of that page in that time span
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if we cannot obtain deleted revisions
 *  @since 0.30
 */
public Revision[] getDeletedHistory(String title, Calendar start, Calendar end, boolean reverse)
    throws IOException, CredentialNotFoundException
{
    // admin queries are annoying
    if (user == null || !user.isAllowedTo("deletedhistory"))
        throw new CredentialNotFoundException("Permission denied: not able to view deleted history");

    StringBuilder url = new StringBuilder(query);
    url.append("prop=deletedrevisions&drvprop=ids%7Cuser%7Cflags%7Csize%7Ccomment&drvlimit=max");
    if (reverse)
        url.append("&drvdir=newer");
    if (start != null)
    {
        url.append(reverse ? "&drvstart=" : "&drvend=");
        url.append(calendarToTimestamp(start));
    }
    if (end != null)
    {
        url.append(reverse ? "&drvend=" : "&drvstart=");
        url.append(calendarToTimestamp(end));
    }
    url.append("&titles=");
    url.append(encode(title, true));

    String drvcontinue = null;
    List<Revision> delrevs = new ArrayList<>(500);
    do
    {
        String response;
        if (drvcontinue != null)
            response = fetch(url.toString() + "&drvcontinue=" + encode(drvcontinue, false), "getDeletedHistory");
        else
            response = fetch(url.toString(), "getDeletedHistory");
        drvcontinue = parseAttribute(response, "drvcontinue", 0);

        // parse
        int x = response.indexOf("<deletedrevs>");
        if (x < 0) // no deleted history
            break;
        for (x = response.indexOf("<page ", x); x > 0; x = response.indexOf("<page ", ++x))
        {
            String deltitle = parseAttribute(response, "title", x);
            int y = response.indexOf("</page>", x);
            for (int z = response.indexOf("<rev ", x); z < y && z >= 0; z = response.indexOf("<rev ", ++z))
            {
                int aa = response.indexOf(" />", z);
                Revision temp = parseRevision(response.substring(z, aa), deltitle);
                temp.pageDeleted = true;
                delrevs.add(temp);
            }
        }
    }
    while (drvcontinue != null);

    int size = delrevs.size();
    log(Level.INFO, "Successfully fetched " + size + " deleted revisions.", "deletedRevs");
    return delrevs.toArray(new Revision[size]);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Gets the deleted contributions of a user in the given namespace. Equivalent to
 *  [[Special:Deletedcontributions]].
 *  @param username a user
 *  @param start the EARLIEST of the two dates
 *  @param end the LATEST of the two dates
 *  @param reverse whether to put the oldest first (default = false, newest
 *  first is how history pages work)
 *  @param namespace a list of namespaces
 *  @return the deleted contributions of that user
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if we cannot obtain deleted revisions
 *  @since 0.30
 */
public Revision[] deletedContribs(String username, Calendar end, Calendar start, boolean reverse, int... namespace)
    throws IOException, CredentialNotFoundException
{
    // admin queries are annoying
    if (user == null || !user.isAllowedTo("deletedhistory"))
        throw new CredentialNotFoundException("Permission denied: not able to view deleted history");

    StringBuilder url = new StringBuilder(query);
    url.append("list=alldeletedrevisions&adrprop=ids%7Cuser%7Cflags%7Csize%7Ccomment%7Ctimestamp&adrlimit=max");
    if (reverse)
        url.append("&adrdir=newer");
    if (start != null)
    {
        url.append(reverse ? "&adrstart=" : "&adrend=");
        url.append(calendarToTimestamp(start));
    }
    if (end != null)
    {
        url.append(reverse ? "&adrend=" : "&adrstart=");
        url.append(calendarToTimestamp(end));
    }
    url.append("&adruser=");
    url.append(encode(username, true));
    constructNamespaceString(url, "adr", namespace);

    String adrcontinue = null;
    List<Revision> delrevs = new ArrayList<>(500);
    do
    {
        String response;
        if (adrcontinue != null)
            response = fetch(url.toString() + "&adrcontinue=" + encode(adrcontinue, false), "deletedContribs");
        else
            response = fetch(url.toString(), "deletedContribs");
        adrcontinue = parseAttribute(response, "adrcontinue", 0);

        // parse
        int x = response.indexOf("<alldeletedrevisions>");
        if (x < 0) // no deleted history
            break;
        for (x = response.indexOf("<page ", x); x > 0; x = response.indexOf("<page ", ++x))
        {
            String deltitle = parseAttribute(response, "title", x);
            int y = response.indexOf("</page>", x);
            for (int z = response.indexOf("<rev ", x); z < y && z >= 0; z = response.indexOf("<rev ", ++z))
            {
                int aa = response.indexOf(" />", z);
                Revision temp = parseRevision(response.substring(z, aa), deltitle);
                temp.pageDeleted = true;
                delrevs.add(temp);
            }
        }
    }
    while (adrcontinue != null);

    int size = delrevs.size();
    log(Level.INFO, "Successfully fetched " + size + " deleted revisions.", "deletedRevs");
    return delrevs.toArray(new Revision[size]);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Unblocks a user. This method is throttled.
 *  @param blockeduser the user to unblock
 *  @param reason the reason for unblocking
 *  @throws CredentialNotFoundException if not an admin
 *  @throws IOException if a network error occurs
 *  @throws CredentialExpiredException if cookies have expired
 *  @throws AccountLockedException if you have been blocked
 *  @since 0.31
 */
public synchronized void unblock(String blockeduser, String reason) throws IOException, LoginException
{
    throttle();
    if (user == null || !user.isA("sysop"))
        throw new CredentialNotFoundException("Cannot unblock: permission denied!");

    // send request
    String request = "user=" + encode(blockeduser, false) +
        "&reason=" + encode(reason, false) + "&token=" +
        encode(getToken("csrf"), false);
    String response = post(query + "action=unblock", request, "unblock");

    // done
    try
    {
        if (!response.contains("<unblock "))
            checkErrorsAndUpdateStatus(response, "unblock");
        else if (response.contains("code=\"cantunblock\""))
            log(Level.INFO, "unblock", blockeduser + " is not blocked.");
        else if (response.contains("code=\"blockedasrange\""))
        {
            log(Level.SEVERE, "unblock", "IP " + blockeduser + " is rangeblocked.");
            return; // throw exception?
        }

    }
    catch (IOException e)
    {
        // retry once
        if (retry)
        {
            retry = false;
            log(Level.WARNING, "undelete", "Exception: " + e.getMessage() + " Retrying...");
            unblock(blockeduser, reason);
        }
        else
        {
            log(Level.SEVERE, "unblock", "EXCEPTION: " + e);
            throw e;
        }
    }
    if (retry)
        log(Level.INFO, "unblock", "Successfully unblocked " + blockeduser);
    retry = true;
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Checks for errors from standard read/write requests and performs
 *  occasional status checks.
 *
 *  @param line the response from the server to analyze
 *  @param caller what we tried to do
 *  @throws CredentialNotFoundException if permission denied
 *  @throws AccountLockedException if the user is blocked
 *  @throws HttpRetryException if the database is locked or action was
 *  throttled and a retry failed
 *  @throws AssertionError if assertions fail
 *  @throws UnknownError in the case of a MediaWiki bug
 *  @since 0.18
 */
protected void checkErrorsAndUpdateStatus(String line, String caller) throws IOException, LoginException
{
    // perform various status checks every 100 or so edits
    if (statuscounter > statusinterval)
    {
        // purge user rights in case of desysop or loss of other priviliges
        user.getUserInfo();
        if ((assertion & ASSERT_SYSOP) == ASSERT_SYSOP && !user.isA("sysop"))
            // assert user.isA("sysop") : "Sysop privileges missing or revoked, or session expired";
            throw new AssertionError("Sysop privileges missing or revoked, or session expired");
        // check for new messages
        if ((assertion & ASSERT_NO_MESSAGES) == ASSERT_NO_MESSAGES && hasNewMessages())
            // assert !hasNewMessages() : "User has new messages";
            throw new AssertionError("User has new messages");
        statuscounter = 0;
    }
    else
        statuscounter++;

    // successful
    if (line.contains("result=\"Success\""))
        return;
    // empty response from server
    if (line.isEmpty())
        throw new UnknownError("Received empty response from server!");
    // assertions
    if ((assertion & ASSERT_BOT) == ASSERT_BOT && line.contains("error code=\"assertbotfailed\""))
        // assert !line.contains("error code=\"assertbotfailed\"") : "Bot privileges missing or revoked, or session expired.";
        throw new AssertionError("Bot privileges missing or revoked, or session expired.");
    if ((assertion & ASSERT_USER) == ASSERT_USER && line.contains("error code=\"assertuserfailed\""))
        // assert !line.contains("error code=\"assertuserfailed\"") : "Session expired.";
        throw new AssertionError("Session expired.");
    if (line.contains("error code=\"permissiondenied\""))
        throw new CredentialNotFoundException("Permission denied."); // session expired or stupidity
    // rate limit (automatic retry), though might be a long one (e.g. email)
    if (line.contains("error code=\"ratelimited\""))
    {
        log(Level.WARNING, caller, "Server-side throttle hit.");
        throw new HttpRetryException("Action throttled.", 503);
    }
    // blocked! (note here the \" in blocked is deliberately missing for emailUser()
    if (line.contains("error code=\"blocked") || line.contains("error code=\"autoblocked\""))
    {
        log(Level.SEVERE, caller, "Cannot " + caller + " - user is blocked!.");
        throw new AccountLockedException("Current user is blocked!");
    }
    // database lock (automatic retry)
    if (line.contains("error code=\"readonly\""))
    {
        log(Level.WARNING, caller, "Database locked!");
        throw new HttpRetryException("Database locked!", 503);
    }
    // unknown error
    if (line.contains("error code=\"unknownerror\""))
        throw new UnknownError("Unknown MediaWiki API error, response was " + line);
    // generic (automatic retry)
    throw new IOException("MediaWiki error, response was " + line);
}
项目:cn1    文件:CredentialNotFoundExceptionTest.java   
@Override
protected Object[] getData() {
    return new Object[] {new CredentialNotFoundException("message")};
}
项目:cn1    文件:CredentialNotFoundExceptionTest.java   
/**
 * @tests javax.security.auth.login.CredentialNotFoundException#CredentialNotFoundException()
 */
public final void testCtor1() {
    assertNull(new CredentialNotFoundException().getMessage());
}
项目:freeVM    文件:CredentialNotFoundExceptionTest.java   
@Override
protected Object[] getData() {
    return new Object[] {new CredentialNotFoundException("message")};
}
项目:freeVM    文件:CredentialNotFoundExceptionTest.java   
/**
 * @tests javax.security.auth.login.CredentialNotFoundException#CredentialNotFoundException()
 */
public final void testCtor1() {
    assertNull(new CredentialNotFoundException().getMessage());
}
项目:freeVM    文件:CredentialNotFoundExceptionTest.java   
@Override
protected Object[] getData() {
    return new Object[] {new CredentialNotFoundException("message")};
}
项目:freeVM    文件:CredentialNotFoundExceptionTest.java   
/**
 * @tests javax.security.auth.login.CredentialNotFoundException#CredentialNotFoundException()
 */
public final void testCtor1() {
    assertNull(new CredentialNotFoundException().getMessage());
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Determines whether a page is watched. (Uses a cache).
 *  @param title the title to be checked
 *  @return whether that page is watched
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if not logged in
 *  @since 0.18
 */
public boolean isWatched(String title) throws IOException, CredentialNotFoundException
{
    // populate the watchlist cache
    if (watchlist == null)
        getRawWatchlist();
    return watchlist.contains(title);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Gets the deleted history of a page.
 *  @param title a page
 *  @return the deleted revisions of that page in that time span
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if we cannot obtain deleted revisions
 *  @since 0.30
 */
public Revision[] getDeletedHistory(String title) throws IOException, CredentialNotFoundException
{
    return getDeletedHistory(title, null, null, false);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Gets the deleted contributions of a user. Equivalent to
 *  [[Special:Deletedcontributions]].
 *  @param u a user
 *  @return the deleted contributions of that user
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if we cannot obtain deleted revisions
 *  @since 0.30
 */
public Revision[] deletedContribs(String u) throws IOException, CredentialNotFoundException
{
    return deletedContribs(u, null, null, false, ALL_NAMESPACES);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Adds a page to the watchlist. You need to be logged in to use this.
 *  @param titles the pages to add to the watchlist
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if not logged in
 *  @see #unwatch
 *  @since 0.18
 */
public void watch(String... titles) throws IOException, CredentialNotFoundException
{
    watchInternal(false, titles);
    watchlist.addAll(Arrays.asList(titles));
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Removes pages from the watchlist. You need to be logged in to use
 *  this. (Does not do anything if the page is not watched).
 *
 *  @param titles the pages to remove from the watchlist.
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if not logged in
 *  @see #watch
 *  @since 0.18
 */
public void unwatch(String... titles) throws IOException, CredentialNotFoundException
{
    watchInternal(true, titles);
    watchlist.removeAll(Arrays.asList(titles));
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Fetches the list of titles on the currently logged in user's watchlist.
 *  Equivalent to [[Special:Watchlist/raw]].
 *  @return the contents of the watchlist
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if not logged in
 *  @since 0.18
 */
public String[] getRawWatchlist() throws IOException, CredentialNotFoundException
{
    return getRawWatchlist(true);
}
项目:discoursedb-core    文件:Wiki.java   
/**
 *  Fetches the most recent changes to pages on your watchlist. Data is
 *  retrieved from the <tt>recentchanges</tt> table and hence cannot be
 *  older than about a month.
 *
 *  @return list of changes to watched pages and their talk pages
 *  @throws IOException if a network error occurs
 *  @throws CredentialNotFoundException if not logged in
 *  @since 0.27
 */
public Revision[] watchlist() throws IOException, CredentialNotFoundException
{
    return watchlist(false);
}