Example usage for java.util HashSet isEmpty

List of usage examples for java.util HashSet isEmpty

Introduction

In this page you can find the example usage for java.util HashSet isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:edu.anu.spice.SemanticConcept.java

public float similarity(Object o) {
    if (o == null) {
        return 0;
    }/*from  w w  w .j a  v a2  s .  com*/
    if (!(o instanceof SemanticConcept)) {
        return 0;
    }
    SemanticConcept otherConcept = (SemanticConcept) o;
    HashSet<String> concept_intersection = new HashSet<String>(this.concepts);
    concept_intersection.retainAll(otherConcept.concepts);
    if (!concept_intersection.isEmpty()) {
        return 1;
    }
    HashSet<Integer> synset_intersection = new HashSet<Integer>(this.synsets);
    synset_intersection.retainAll(otherConcept.synsets);
    HashSet<Integer> synset_union = new HashSet<Integer>(this.synsets);
    synset_union.addAll(otherConcept.synsets);
    return ((float) synset_intersection.size()) / ((float) synset_union.size());
}

From source file:com.appunite.socketio.SocketIOBase.java

private ImmutableSet<String> getTypesFromString(String str) throws WrongSocketIOResponse {
    StringTokenizer st = new StringTokenizer(str, ",");
    HashSet<String> types = new HashSet<String>();
    while (st.hasMoreTokens()) {
        types.add(st.nextToken());// www .j  a  va  2 s  .  co  m
    }
    if (types.isEmpty())
        throw new WrongSocketIOResponse("No transport types in socket response");
    return ImmutableSet.copyOf(types);
}

From source file:com.ryan.ryanreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Fragment fragmentParent,
        final Action action) {

    final Activity activity = fragmentParent.getSupportActivity();

    switch (action) {

    case UPVOTE:// w w w  .  ja  v a2  s .c  o  m
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(post.url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            General.copyFile(cacheFile.getInputStream(), dst);
                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        final RedditSubreddit subreddit = new RedditSubreddit("/r/" + post.src.subreddit,
                "/r/" + post.src.subreddit, true);

        final Intent intent = new Intent(activity, PostListingActivity.class);
        intent.putExtra("subreddit", subreddit);
        activity.startActivityForResult(intent, 1);
        break;
    }

    case USER_PROFILE:
        UserProfileDialog.newInstance(post.src.author).show(activity);
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, fragmentParent, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:pt.ist.maidSyncher.domain.SynchableObject.java

protected static SynchableObject findOrCreateAndProccess(Object object, Class<? extends SynchableObject> clazz,
        Iterable iterable, boolean skipGenerateSyncEvent, ObjectFindStrategy... optionalObjectFindStrategy)
        throws SyncEventIllegalConflict {
    SynchableObject toProccessAndReturn = null;
    checkNotNull(object);/*from w w  w .ja  va 2 s .  c  o  m*/
    checkNotNull(iterable);
    //        checkArgument(clazz.isAssignableFrom(object.getClass()),
    //                "Object's class must be a class (or superclass) of " + clazz.getName());

    ObjectFindStrategy optionalObjectFindStrategyToBeUsed = null;
    if (optionalObjectFindStrategy == null || optionalObjectFindStrategy.length == 0) {
        optionalObjectFindStrategyToBeUsed = ObjectFindStrategy.FIND_BY_ID;
    } else if (optionalObjectFindStrategy.length >= 1) {
        optionalObjectFindStrategyToBeUsed = optionalObjectFindStrategy[0];
    }

    Optional<SynchableObject> synchableObject = optionalObjectFindStrategyToBeUsed.find(object, clazz,
            iterable);
    if (synchableObject.isPresent()) {
        toProccessAndReturn = synchableObject.get();
    } else {
        //let's create it
        try {
            toProccessAndReturn = clazz.getConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            if (e.getCause() instanceof WriteOnReadError)
                throw (WriteOnReadError) e.getCause();
            throw new UnsupportedOperationException(
                    "Class: " + clazz.getName() + " has no usable, simple, e.g. Constructor() constructor", e);
        }
    }

    //let's copy the values
    HashSet<String> changedDescriptors = new HashSet<>();
    try {
        changedDescriptors.addAll(toProccessAndReturn.copyPropertiesFrom(object));
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        if (e.getCause() instanceof WriteOnReadError)
            throw ((WriteOnReadError) e.getCause());
        throw new IllegalArgumentException("There were problems copying properties from object of class "
                + object.getClass().getName() + " to " + toProccessAndReturn.getClass().getName() + " oid: "
                + toProccessAndReturn.getExternalId(), e);
    }

    if (!skipGenerateSyncEvent && changedDescriptors.isEmpty() == false) {
        //we changed something, let's create and add the syncEvent to the ChangesBuzz
        generateSyncEvent(toProccessAndReturn, changedDescriptors, object);
    } else if (skipGenerateSyncEvent == true && toProccessAndReturn.getDSIObject() == null) {
        //we should create the DSIObject on this file
        try {
            toProccessAndReturn.findOrCreateDSIObject();
        } catch (UnsupportedOperationException ex) {
            //continue silently
        }

    }

    return toProccessAndReturn;

}

From source file:com.pinterest.arcee.aws.EC2HostInfoDAOImpl.java

@Override
public List<String> getRunningInstances(List<String> runningIds) throws Exception {
    HashSet<String> ids = new HashSet<>(runningIds);
    ArrayList<String> resultIds = new ArrayList<>();
    while (!ids.isEmpty()) {
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setInstanceIds(ids);/*from w  ww  . j ava 2 s  .co m*/
        Filter filter = new Filter("instance-state-code", Arrays.asList(RUNNING_CODE));
        request.setFilters(Arrays.asList(filter));
        try {
            do {
                DescribeInstancesResult results = ec2Client.describeInstances(request);
                List<Reservation> reservations = results.getReservations();
                for (Reservation reservation : reservations) {
                    for (Instance instance : reservation.getInstances()) {
                        resultIds.add(instance.getInstanceId());
                    }
                }
                if (StringUtils.isEmpty(results.getNextToken())) {
                    break;
                }

                request = new DescribeInstancesRequest();
                request.setNextToken(results.getNextToken());
            } while (true);
            LOG.debug("Cannot find the following ids in AWS:", ids);
            return resultIds;
        } catch (AmazonServiceException ex) {
            // if the error code is not instance not found. return the terminated list we've already got.
            ids.removeAll(handleInvalidInstanceId(ex));
        } catch (AmazonClientException ex) {
            LOG.error(String.format("Get AmazonClientException, exit with terminiatedHost %s",
                    resultIds.toString()), ex);
            throw new Exception(String.format("Get AmazonClientException, exit with terminiatedHost %s",
                    resultIds.toString()), ex);
        }
    }
    return resultIds;
}

From source file:com.pinterest.arcee.aws.EC2HostInfoDAOImpl.java

@Override
public Set<String> getTerminatedHosts(Set<String> staleIds) throws Exception {
    HashSet<String> ids = new HashSet<>(staleIds);
    HashSet<String> terminatedHosts = new HashSet<>();
    while (!ids.isEmpty()) {
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setInstanceIds(ids);//  ww w  .  j ava 2s . co m
        try {
            do {
                DescribeInstancesResult results = ec2Client.describeInstances(request);
                List<Reservation> reservations = results.getReservations();
                for (Reservation reservation : reservations) {
                    for (Instance instance : reservation.getInstances()) {
                        int stateCode = instance.getState().getCode();
                        String id = instance.getInstanceId();
                        if (stateCode == TERMINATED_CODE || stateCode == STOPPED_CODE) {
                            LOG.info(String.format("Instance %s has already been terminated or stopped.", id));
                            terminatedHosts.add(id);
                        }

                        ids.remove(id);
                    }
                }
                if (results.getNextToken() == null || results.getNextToken().isEmpty()) {
                    break;
                }
                request = new DescribeInstancesRequest();
                request.setInstanceIds(ids);
                request.setNextToken(results.getNextToken());
            } while (true);
            LOG.debug("Cannot find the following ids in AWS:", ids);
            terminatedHosts.addAll(ids);
            return terminatedHosts;
        } catch (AmazonServiceException ex) {
            Collection<String> invalidHostIds = handleInvalidInstanceId(ex);
            ids.removeAll(invalidHostIds);
            // add invalid host ids to the terminated host list.
            terminatedHosts.addAll(invalidHostIds);
        } catch (AmazonClientException ex) {
            LOG.error(String.format("Get AmazonClientException, exit with terminiatedHost %s",
                    terminatedHosts.toString()), ex);
            return terminatedHosts;
        }
    }
    return terminatedHosts;
}

From source file:Business.InvertedIndex.java

public List searchForWholePhrase(List<DocInfo> docList, String[] queryTerms) {

    HashMap<DocInfo, Integer> documentPhraseScore = new HashMap<>();

    for (DocInfo doc : docList) {
        documentPhraseScore.put(doc, 0);
        int count = 0;
        for (String word1 : queryTerms) {
            String word2 = word1.replaceAll("[^\\w]", "");
            es.setCurrent(word2);/*from  ww w.  j  a  v  a2s .c  o  m*/
            es.stem();
            String queryTerm = es.getCurrent();
            HashSet<Integer> positions = new HashSet<>();

            if (doc.getTermsInADocument().containsKey(queryTerm)) {
                if (positions.isEmpty()) {
                    positions.addAll(doc.getTermsInADocument().get(queryTerm).getPositions());
                } else {
                    ArrayList<Integer> newPositions = doc.getTermsInADocument().get(queryTerm).getPositions();
                    ArrayList<Integer> tempList = new ArrayList<>();
                    boolean b = false;
                    for (int po : newPositions) {

                        if (positions.contains(po - 1)) {
                            tempList.add(po);
                            int currentScore = documentPhraseScore.get(doc);
                            int newScore = currentScore + count;
                            documentPhraseScore.put(doc, newScore);
                            b = true;
                        }
                    }
                    if (b) {
                        positions.clear();
                        positions.addAll(tempList);
                    }
                }
            }
            if (count == 0) {
                count++;
            } else {
                count = count * 10;
            }
        }

    }

    Set<DocInfo> set = documentPhraseScore.keySet();
    List<DocInfo> sortedDocs = new ArrayList<>(set);

    Collections.sort(sortedDocs, (DocInfo s1, DocInfo s2) -> Double.compare(documentPhraseScore.get(s2),
            documentPhraseScore.get(s1)));
    return sortedDocs;
}

From source file:it.unibas.spicygui.controllo.mapping.ActionGenerateAndTranslate.java

private void checkForPKConstraints(MappingTask mappingTask, HashSet<String> pkTableNames, int scenarioNo)
        throws DAOException {
    if (!pkTableNames.isEmpty()) {
        NotifyDescriptor notifyDescriptor = new NotifyDescriptor.Confirmation(
                NbBundle.getMessage(Costanti.class, Costanti.MESSAGE_PK_TABLES),
                DialogDescriptor.YES_NO_OPTION);
        DialogDisplayer.getDefault().notify(notifyDescriptor);
        if (notifyDescriptor.getValue().equals(NotifyDescriptor.YES_OPTION)) {
            String[] format = { NbBundle.getMessage(Costanti.class, Costanti.OUTPUT_TYPE_CSV),
                    NbBundle.getMessage(Costanti.class, Costanti.OUTPUT_TYPE_JSON) };
            int formatResponse = JOptionPane.showOptionDialog(null,
                    NbBundle.getMessage(Costanti.class, Costanti.MESSAGE_PK_OUTPUT),
                    NbBundle.getMessage(Costanti.class, Costanti.PK_OUTPUT_TITLE), JOptionPane.DEFAULT_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, format, format[0]);
            if (formatResponse != JOptionPane.CLOSED_OPTION) {
                JFileChooser chooser = vista.getFileChooserSalvaFolder();
                File file;/*from   w  w  w .  j  a v a 2s  .  c  om*/
                int returnVal = chooser.showDialog(WindowManager.getDefault().getMainWindow(),
                        NbBundle.getMessage(Costanti.class, Costanti.EXPORT));
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file = chooser.getSelectedFile();
                    if (formatResponse == 0) {
                        DAOCsv daoCsv = new DAOCsv();
                        daoCsv.exportPKConstraintCSVinstances(mappingTask, pkTableNames, file.getAbsolutePath(),
                                scenarioNo);
                        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                                NbBundle.getMessage(Costanti.class, Costanti.EXPORT_COMPLETED_OK)));
                    } else if (formatResponse == 1) {
                        DAOJson daoJson = new DAOJson();
                        daoJson.exportPKConstraintJsoninstances(mappingTask, pkTableNames,
                                file.getAbsolutePath(), scenarioNo);
                        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                                NbBundle.getMessage(Costanti.class, Costanti.EXPORT_COMPLETED_OK)));
                    }
                }
            }
        }
    }
}

From source file:org.lol.reddit.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity,
        final Action action) {

    switch (action) {

    case UPVOTE://  w w  w. jav  a  2  s .  c  om
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl()
                : post.url;
        intent.setData(Uri.parse(url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status,
                                url.toString());
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            final InputStream cacheFileInputStream = cacheFile.getInputStream();

                            if (cacheFileInputStream == null) {
                                notifyFailure(RequestFailureType.CACHE_MISS, null, null,
                                        "Could not find cached image");
                                return;
                            }

                            General.copyFile(cacheFileInputStream, dst);

                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        try {
            final Intent intent = new Intent(activity, PostListingActivity.class);
            intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).generateJsonUri());
            activity.startActivityForResult(intent, 1);

        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show();
        }

        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.author).toString());
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:org.droidparts.persist.sql.EntityManager.java

@Override
public void fillForeignKeys(EntityType item, String... columnNames) {
    HashSet<String> columnNameSet = new HashSet<String>(asList(columnNames));
    boolean fillAll = columnNameSet.isEmpty();
    for (FieldSpec<ColumnAnn> spec : getTableColumnSpecs(cls)) {
        if (isEntity(spec.field.getType()) && (fillAll || columnNameSet.contains(spec.ann.name))) {
            Entity foreignEntity = ReflectionUtils.getFieldVal(item, spec.field);
            if (foreignEntity != null) {
                Object obj = subManager(spec.field).read(foreignEntity.id);
                setFieldVal(item, spec.field, obj);
            }// w  w  w  . j  a v a  2s .c o m
        }
    }
}