Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

In this page you can find the example usage for java.lang SecurityException SecurityException.

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.sakaiproject.iclicker.logic.IClickerLogic.java

/**
 * This returns an item based on a clickerId and ownerId if the user is allowed to access it,
 * this will return a null if the clickerId is invalid or cannot be found
 * //from   w ww  .  j  av  a  2s  . c om
 * @param clickerId the clicker remote ID
 * @param ownerId the clicker owner ID (user id)
 * @return a ClickerRegistration OR null if none found
 * @throws SecurityException if the current user cannot access this item
 */
public ClickerRegistration getItemByClickerId(String clickerId, String ownerId) {
    log.debug("Getting item by clickerId: " + clickerId);
    String userId = externalLogic.getCurrentUserId();
    if (userId == null) {
        throw new SecurityException("user must be logged in");
    }
    if (ownerId != null) {
        userId = ownerId;
    }
    try {
        clickerId = validateClickerId(clickerId);
    } catch (ClickerIdInvalidException e) {
        return null;
    }
    ClickerRegistration item = dao.findOneBySearch(ClickerRegistration.class, new Search(
            new Restriction[] { new Restriction("clickerId", clickerId), new Restriction("ownerId", userId) }));
    if (item != null) {
        if (!canReadItem(item, externalLogic.getCurrentUserId())) {
            throw new SecurityException("User (" + externalLogic.getCurrentUserId()
                    + ") not allowed to access registration (" + item + ")");
        }
    }
    return item;
}

From source file:com.thebuzzmedia.exiftool.ExifTool.java

private Map<String, String> getImageMeta(final File image, final Format format,
        final boolean suppressDuplicates, final String... tags)
        throws IllegalArgumentException, SecurityException, IOException {

    // Validate input and create Arg Array
    final boolean stayOpen = featureSet.contains(Feature.STAY_OPEN);
    List<String> args = new ArrayList<String>(tags.length + 4);
    if (format == null) {
        throw new IllegalArgumentException("format cannot be null");
    } else if (format == Format.NUMERIC) {
        args.add("-n"); // numeric output
    }/*ww  w.ja  v a 2  s.c o  m*/
    if (!suppressDuplicates) {
        args.add("-a"); // suppress duplicates
    }
    args.add("-S"); // compact output

    if (tags == null || tags.length == 0) {
        throw new IllegalArgumentException(
                "tags cannot be null and must contain 1 or more Tag to query the image for.");
    }
    for (String tag : tags) {
        args.add("-" + tag);
    }
    if (image == null) {
        throw new IllegalArgumentException("image cannot be null and must be a valid stream of image data.");
    }
    if (!image.canRead()) {
        throw new SecurityException("Unable to read the given image [" + image.getAbsolutePath()
                + "], ensure that the image exists at the given path and that the executing Java process has permissions to read it.");
    }
    args.add(image.getAbsolutePath());

    // start process
    long startTime = System.currentTimeMillis();
    log.debug(String.format("Querying %d tags from image: %s", tags.length, image.getAbsolutePath()));
    /*
     * Using ExifTool in daemon mode (-stay_open True) executes different
     * code paths below. So establish the flag for this once and it is
     * reused a multitude of times later in this method to figure out where
     * to branch to.
     */
    Map<String, String> resultMap;
    if (stayOpen) {
        log.debug("Using ExifTool in daemon mode (-stay_open True)...");
        resultMap = processStayOpen(args);
    } else {
        log.debug("Using ExifTool in non-daemon mode (-stay_open False)...");
        resultMap = ExifProcess.executeToResults(exifCmd, args);
    }

    // Print out how long the call to external ExifTool process took.
    if (log.isDebugEnabled()) {
        log.debug(String.format("Image Meta Processed in %d ms [queried %d tags and found %d values]",
                (System.currentTimeMillis() - startTime), tags.length, resultMap.size()));
    }

    return resultMap;
}

From source file:com.thebuzzmedia.exiftool.ExifToolNew3.java

@Override
public Map<String, String> getImageMeta(File file, ReadOptions readOptions, String... tags) throws IOException {
    // Validate input and create Arg Array
    final boolean stayOpen = featureSet.contains(Feature.STAY_OPEN);
    if (tags == null) {
        tags = new String[0];
    }//  w w  w .  ja  v a2  s .c  o m
    List<String> args = new ArrayList<String>(tags.length + 4);
    if (readOptions == null) {
        throw new IllegalArgumentException("format cannot be null");
    } else if (readOptions.numericOutput) {
        args.add("-n"); // numeric output
    }
    if (readOptions.showDuplicates) {
        // args.add("-a");
        args.add("-duplicates"); // allow duplicates to be shown
    }
    // -S or -veryShort
    args.add("-veryShort"); // compact output
    for (String tag : tags) {
        args.add("-" + tag);
    }
    if (file == null) {
        throw new IllegalArgumentException("image cannot be null and must be a valid stream of image data.");
    }
    if (!file.canRead()) {
        throw new SecurityException("Unable to read the given image [" + file.getAbsolutePath()
                + "], ensure that the image exists at the given path and that the executing Java process has permissions to read it.");
    }
    String absoluteName = getAbsoluteFileName(file);
    String fileName = absoluteName;
    File tempFileName = null;
    if (absoluteName == null) {
        tempFileName = getTemporaryCopiedFileName(file);
        fileName = tempFileName.getAbsolutePath();
        LOG.info("Exiftool will work with temporary file " + fileName + " for original file [" + absoluteName
                + "].");
    }
    Map<String, String> resultMap;
    try {
        args.add(fileName);

        // start process
        long startTime = System.currentTimeMillis();
        LOG.debug(String.format("Querying %d tags from image: %s", tags.length, file.getAbsolutePath()));
        LOG.info("call stayOpen=" + stayOpen + " exiftool " + Joiner.on(" ").join(args));
        /*
         * Using ExifToolNew3 in daemon mode (-stay_open True) executes different code paths below. So establish the
         * flag for this once and it is reused a multitude of times later in this method to figure out where to
         * branch to.
         */
        if (stayOpen) {
            LOG.debug("Using ExifToolNew3 in daemon mode (-stay_open True)...");
            resultMap = processStayOpen(args);
        } else {
            LOG.debug("Using ExifToolNew3 in non-daemon mode (-stay_open False)...");
            resultMap = ExifToolService.toMap(execute(args));
        }

        // Print out how long the call to external ExifToolNew3 process took.
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Image Meta Processed in %d ms [queried %d tags and found %d values]",
                    (System.currentTimeMillis() - startTime), tags.length, resultMap.size()));
        }
    } finally {
        if (tempFileName != null) {
            FileUtils.forceDelete(tempFileName);
        }
    }
    return resultMap;
}

From source file:org.opencastproject.workflow.impl.WorkflowServiceImpl.java

/**
 * {@inheritDoc}/*  w w w.j a  v a  2  s  .co m*/
 * 
 * @see org.opencastproject.workflow.api.WorkflowService#start(org.opencastproject.workflow.api.WorkflowDefinition,
 *      org.opencastproject.mediapackage.MediaPackage, Long, java.util.Map)
 */
@Override
public WorkflowInstance start(WorkflowDefinition workflowDefinition, MediaPackage sourceMediaPackage,
        Long parentWorkflowId, Map<String, String> properties)
        throws WorkflowDatabaseException, WorkflowParsingException, NotFoundException {

    if (workflowDefinition == null)
        throw new IllegalArgumentException("workflow definition must not be null");
    if (sourceMediaPackage == null)
        throw new IllegalArgumentException("mediapackage must not be null");
    for (List<String> errors : MediaPackageSupport.sanityCheck(sourceMediaPackage)) {
        throw new IllegalArgumentException(
                "Insane media package cannot be processed: " + mkString(errors, "; "));
    }
    if (parentWorkflowId != null) {
        try {
            getWorkflowById(parentWorkflowId); // Let NotFoundException bubble up
        } catch (UnauthorizedException e) {
            throw new IllegalArgumentException(
                    "Parent workflow " + parentWorkflowId + " not visible to this user");
        }
    }

    // Get the current user
    User currentUser = securityService.getUser();
    if (currentUser == null)
        throw new SecurityException("Current user is unknown");

    // Get the current organization
    Organization organization = securityService.getOrganization();
    if (organization == null)
        throw new SecurityException("Current organization is unknown");

    WorkflowInstance workflowInstance = new WorkflowInstanceImpl(workflowDefinition, sourceMediaPackage,
            parentWorkflowId, currentUser, organization, properties);
    workflowInstance = updateConfiguration(workflowInstance, properties);

    // Create and configure the workflow instance
    try {
        // Create a new job for this workflow instance
        String workflowDefinitionXml = WorkflowParser.toXml(workflowDefinition);
        String workflowInstanceXml = WorkflowParser.toXml(workflowInstance);
        String mediaPackageXml = MediaPackageParser.getAsXml(sourceMediaPackage);

        List<String> arguments = new ArrayList<String>();
        arguments.add(workflowDefinitionXml);
        arguments.add(mediaPackageXml);
        if (parentWorkflowId != null || properties != null) {
            String parentWorkflowIdString = (parentWorkflowId != null) ? parentWorkflowId.toString()
                    : NULL_PARENT_ID;
            arguments.add(parentWorkflowIdString);
        }
        if (properties != null) {
            arguments.add(mapToString(properties));
        }

        Job job = serviceRegistry.createJob(JOB_TYPE, Operation.START_WORKFLOW.toString(), arguments,
                workflowInstanceXml, false, null);

        // Have the workflow take on the job's identity
        workflowInstance.setId(job.getId());

        // Add the workflow to the search index and have the job enqueued for dispatch.
        // Update also sets ACL and mediapackage metadata
        update(workflowInstance);

        return workflowInstance;
    } catch (Throwable t) {
        try {
            workflowInstance.setState(FAILED);
            update(workflowInstance);
        } catch (Exception failureToFail) {
            logger.warn("Unable to update workflow to failed state", failureToFail);
        }
        throw new WorkflowDatabaseException(t);
    }
}

From source file:org.openmrs.module.ModuleUtil.java

/**
 * Convenience method to follow http to https redirects. Will follow a total of 5 redirects,
 * then fail out due to foolishness on the url's part.
 *
 * @param c the {@link URLConnection} to open
 * @return an {@link InputStream} that is not necessarily at the same url, possibly at a 403
 *         redirect./*from w w  w. j a  v a 2  s . c  om*/
 * @throws IOException
 * @see #getURLStream(URL)
 */
protected static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException {
    boolean redir;
    int redirects = 0;
    InputStream in = null;
    do {
        if (c instanceof HttpURLConnection) {
            ((HttpURLConnection) c).setInstanceFollowRedirects(false);
        }
        // We want to open the input stream before getting headers
        // because getHeaderField() et al swallow IOExceptions.
        in = c.getInputStream();
        redir = false;
        if (c instanceof HttpURLConnection) {
            HttpURLConnection http = (HttpURLConnection) c;
            int stat = http.getResponseCode();
            if (stat == 300 || stat == 301 || stat == 302 || stat == 303 || stat == 305 || stat == 307) {
                URL base = http.getURL();
                String loc = http.getHeaderField("Location");
                URL target = null;
                if (loc != null) {
                    target = new URL(base, loc);
                }
                http.disconnect();
                // Redirection should be allowed only for HTTP and HTTPS
                // and should be limited to 5 redirections at most.
                if (target == null
                        || !("http".equals(target.getProtocol()) || "https".equals(target.getProtocol()))
                        || redirects >= 5) {
                    throw new SecurityException("illegal URL redirect");
                }
                redir = true;
                c = target.openConnection();
                redirects++;
            }
        }
    } while (redir);
    return in;
}

From source file:org.openanzo.activemq.internal.SecurityBroker.java

@Override
public void send(ProducerBrokerExchange exchange, Message messageSend) throws Exception {
    final ServerSecurityContext subject = (ServerSecurityContext) exchange.getConnectionContext()
            .getSecurityContext();/*from  ww  w. j  a v  a  2 s  . c o  m*/
    if (subject == null) {
        MDC.put(LogUtils.REMOTE_ADDRESS, exchange.getConnectionContext().getConnection().getRemoteAddress());
        String errorMsg = Messages.formatString(ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED,
                exchange.getConnectionContext().getConnectionId().toString());
        log.error(LogUtils.SECURITY_MARKER, errorMsg);
        MDC.clear();
        throw new SecurityException(errorMsg);
    }
    if (!subject.getAuthorizedWriteDests().contains(messageSend.getDestination())) {
        if (serverQueueNames.contains(messageSend.getDestination().getPhysicalName()) || messageSend
                .getDestination().getPhysicalName().startsWith(NAMESPACES.NAMEDGRAPH_TOPIC_PREFIX)) {
            if (!subject.getAnzoPrincipal().isSysadmin()) {
                MDC.put(LogUtils.REMOTE_ADDRESS,
                        exchange.getConnectionContext().getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                String errorMsg = Messages.formatString(
                        ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED, subject.getUserName(),
                        "write", messageSend.getDestination().toString());
                log.info(LogUtils.SECURITY_MARKER, errorMsg);
                MDC.clear();
                throw new SecurityException(errorMsg);
            }
        } else if (messageSend.getDestination().getPhysicalName().startsWith(NAMESPACES.STREAM_TOPIC_PREFIX)) {
            if (primaryDatasource == null) {
                MDC.put(LogUtils.REMOTE_ADDRESS,
                        exchange.getConnectionContext().getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                String logMsg = Messages.formatString(ExceptionConstants.COMBUS.ERROR_SERVER_NOT_READY);
                log.warn(LogUtils.COMBUS_MARKER, logMsg);
                MDC.clear();
                throw new SecurityException(logMsg);
            }
            IOperationContext opContext = null;
            try {
                opContext = new BaseOperationContext(SEND_MESSAGE,
                        exchange.getConnectionContext().getConnectionId().toString(), principal);
                opContext.setMDC();
                if (!subject.getAnzoPrincipal().isSysadmin()) {
                    String namedGraphUUIDUri = UriGenerator.stripEncapsulatedString(
                            NAMESPACES.STREAM_TOPIC_PREFIX, messageSend.getDestination().getPhysicalName());
                    URI namedGraphUri = null;
                    try {
                        namedGraphUri = primaryDatasource.getModelService().getUriForUUID(opContext,
                                Constants.valueFactory.createURI(namedGraphUUIDUri));
                    } catch (AnzoException e) {
                        String logMsg = Messages.formatString(
                                ExceptionConstants.DATASOURCE.NAMEDGRAPH.GRAPH_NOT_VALID, namedGraphUUIDUri);
                        log.debug(LogUtils.COMBUS_MARKER, logMsg, e);
                        throw new SecurityException(logMsg, e);
                    }
                    if (namedGraphUri == null) {
                        String logMsg = Messages.formatString(
                                ExceptionConstants.DATASOURCE.NAMEDGRAPH.GRAPH_NOT_VALID, namedGraphUUIDUri);
                        log.debug(LogUtils.COMBUS_MARKER, logMsg);
                        throw new SecurityException(logMsg);
                    }
                    Set<URI> roles = primaryDatasource.getAuthorizationService().getRolesForGraph(opContext,
                            namedGraphUri, Privilege.ADD);
                    if (!org.openanzo.rdf.utils.Collections.memberOf(roles,
                            subject.getAnzoPrincipal().getRoles())) {
                        MDC.put(LogUtils.REMOTE_ADDRESS,
                                exchange.getConnectionContext().getConnection().getRemoteAddress());
                        MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                        String errorMsg = Messages.formatString(
                                ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED,
                                subject.getUserName(), "write", messageSend.getDestination().toString());
                        log.info(LogUtils.SECURITY_MARKER, errorMsg);
                        MDC.clear();
                        throw new SecurityException(errorMsg);
                    }
                    subject.getAuthorizedWriteDests().put(messageSend.getDestination(),
                            messageSend.getDestination());
                    messageSend.setProperty(SerializationConstants.userUri,
                            subject.getAnzoPrincipal().getUserURI().toString());
                }
            } finally {
                if (opContext != null) {
                    opContext.clearMDC();
                }
            }
        } /*else if (messageSend.getDestination().getPhysicalName().startsWith("services/")) {
                     Set<Destination> dests = next.getDestinations(messageSend.getDestination());
                     if (dests == null || dests.size() == 0) {
                         if (messageSend.getReplyTo() != null && messageSend.getCorrelationId() != null) {
                             Message reply = messageSend.copy();
                             reply.setDestination(messageSend.getReplyTo());
                             try {
                                 reply.clearBody();
                             } catch (javax.jms.JMSException e) {
                  
                             }
                             reply.setProperty("error", "true");
                             next.send(exchange, reply);
                         }
                         //throw new IllegalArgumentException("User " + subject.getUserName() + " is not authorized to publish to: " + messageSend.getDestination() + " since is does not yet exist");
                     }
                 }*/
        subject.getAuthorizedWriteDests().put(messageSend.getDestination(), messageSend.getDestination());
    }
    super.send(exchange, messageSend);
    //     } finally {
    //         resetlock.readLock().unlock();
    //     }
}

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

private void checkWritePermission(final int id, final String table) {
    switch (id) {
    case TABLE_ID_ACCOUNTS: {
        // Writing to accounts database is not allowed for third-party
        // applications.
        if (!mPermissionsManager.checkSignature(Binder.getCallingUid()))
            throw new SecurityException(
                    "Writing to accounts database is not allowed for third-party applications");
        break;//from  w ww.j  av  a  2  s. c  om
    }
    case TABLE_ID_DIRECT_MESSAGES:
    case TABLE_ID_DIRECT_MESSAGES_INBOX:
    case TABLE_ID_DIRECT_MESSAGES_OUTBOX:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRIES: {
        if (!checkPermission(PERMISSION_DIRECT_MESSAGES))
            throw new SecurityException(
                    "Access database " + table + " requires level PERMISSION_LEVEL_DIRECT_MESSAGES");
        break;
    }
    case TABLE_ID_STATUSES:
    case TABLE_ID_MENTIONS:
    case TABLE_ID_TABS:
    case TABLE_ID_DRAFTS:
    case TABLE_ID_CACHED_USERS:
    case TABLE_ID_FILTERED_USERS:
    case TABLE_ID_FILTERED_KEYWORDS:
    case TABLE_ID_FILTERED_SOURCES:
    case TABLE_ID_FILTERED_LINKS:
    case TABLE_ID_TRENDS_LOCAL:
    case TABLE_ID_CACHED_STATUSES:
    case TABLE_ID_CACHED_HASHTAGS: {
        if (!checkPermission(PERMISSION_WRITE))
            throw new SecurityException("Access database " + table + " requires level PERMISSION_LEVEL_WRITE");
        break;
    }
    }
}

From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java

@Test
public void doDecryptRecordsErrorForSecurityException() throws Exception {
    // Need to actually generate a zip with a valid checksum so calling export
    configurationMigrationManager.doExport(path);

    doThrow(new SecurityException("testing")).when(configurationMigrationManager)
            .delegateToDecryptMigrationManager(any(MigrationReportImpl.class), any(MigrationZipFile.class),
                    any(Path.class));

    MigrationReport report = configurationMigrationManager.doDecrypt(path);

    reportHasErrorMessage(report.errors(),
            equalTo("Decrypt security error: failed to decrypt file [" + encryptedFileName + "]; testing."));
    verify(configurationMigrationManager).delegateToDecryptMigrationManager(any(MigrationReportImpl.class),
            any(MigrationZipFile.class), eq(Paths.get(decryptedFileName)));
    verifyZipEncryptedFile();//w w w.  j  a  va2s . co  m
    verifyZeroInteractions(mockSystemService);
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

private void checkSessionIdChannelBinding(AuthenticationDataMessage message, HttpServletRequest request) {
    LOG.debug("using TLS session Id channel binding");
    byte[] sessionId = message.sessionId;
    /*/*from  w ww.j a va  2 s .  co  m*/
     * Next is Tomcat specific.
     */
    String actualSessionId = (String) request.getAttribute("javax.servlet.request.ssl_session");
    if (null == actualSessionId) {
        /*
         * Servlet specs v3.0
         */
        actualSessionId = (String) request.getAttribute("javax.servlet.request.ssl_session_id");
    }
    if (null == actualSessionId) {
        LOG.warn("could not verify the SSL session identifier");
        return;
    }
    if (false == Arrays.equals(sessionId, Hex.decode(actualSessionId))) {
        LOG.warn("SSL session Id mismatch");
        LOG.debug("signed SSL session Id: " + new String(Hex.encode(sessionId)));
        LOG.debug("actual SSL session Id: " + actualSessionId);
        throw new SecurityException("SSL session Id mismatch");
    }
    LOG.debug("SSL session identifier checked");
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * check if mLocalFile exists.//from   ww  w . j a va  2  s.co m
 *
 * @return true if file exists and match md5sum and sha1sum.
 * @throws java.util.concurrent.CancellationException when check is cancelled by user
 * @throws SecurityException bad file permissions
 * @throws IOException when IOException occurs
 * @throws java.security.NoSuchAlgorithmException when digests cannot be created
 * @throws java.security.KeyException when file checksum fails
 */
private boolean haveLocalFile()
        throws CancellationException, SecurityException, IOException, NoSuchAlgorithmException, KeyException {

    File file = null;
    InputStream reader = null;
    boolean exitForError = true;

    if (mCurrentTask.path == null)
        return false;

    try {
        MessageDigest md5, sha1;
        byte[] buffer;
        int read;
        short percentage, previous_percentage;
        long read_counter, total;

        file = new File(mCurrentTask.path);
        buffer = new byte[4096];
        total = file.length();
        read_counter = 0;
        previous_percentage = -1;

        if (!file.exists() || !file.isFile())
            return false;

        if (!file.canWrite() || !file.canRead()) {
            read = -1;
            try {
                read = Shell.exec(String.format("chmod 777 '%s'", mCurrentTask.path));
            } catch (Exception e) {
                System.errorLogging(e);
            }
            if (read != 0)
                throw new SecurityException(String.format("bad file permissions for '%s', chmod returned: %d",
                        mCurrentTask.path, read));
        }

        if (mCurrentTask.md5 != null || mCurrentTask.sha1 != null) {
            mBuilder.setContentTitle(getString(R.string.checking))
                    .setSmallIcon(android.R.drawable.ic_popup_sync).setContentText("")
                    .setProgress(100, 0, false);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

            md5 = (mCurrentTask.md5 != null ? MessageDigest.getInstance("MD5") : null);
            sha1 = (mCurrentTask.sha1 != null ? MessageDigest.getInstance("SHA-1") : null);

            reader = new FileInputStream(file);
            while (mRunning && (read = reader.read(buffer)) != -1) {
                if (md5 != null)
                    md5.update(buffer, 0, read);
                if (sha1 != null)
                    sha1.update(buffer, 0, read);

                read_counter += read;

                percentage = (short) (((double) read_counter / total) * 100);
                if (percentage != previous_percentage) {
                    mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                    previous_percentage = percentage;
                }
            }
            reader.close();
            reader = null;
            if (!mRunning) {
                exitForError = false;
                throw new CancellationException("local file check cancelled");
            }
            if (md5 != null && !mCurrentTask.md5.equals(digest2string(md5.digest())))
                throw new KeyException("wrong MD5");
            if (sha1 != null && !mCurrentTask.sha1.equals(digest2string(sha1.digest())))
                throw new KeyException("wrong SHA-1");
            Logger.info(String.format("checksum ok: '%s'", mCurrentTask.path));
        } else if (mCurrentTask.archiver != null) {
            verifyArchiveIntegrity();
        }
        Logger.info(String.format("file already exists: '%s'", mCurrentTask.path));
        mBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done)
                .setContentTitle(getString(R.string.update_available))
                .setContentText(getString(R.string.click_here_to_upgrade)).setProgress(0, 0, false) // remove progress bar
                .setAutoCancel(true);
        exitForError = false;
        return true;
    } finally {
        if (exitForError && file != null && file.exists() && !file.delete())
            Logger.error(String.format("cannot delete local file '%s'", mCurrentTask.path));
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            System.errorLogging(e);
        }
    }
}