List of usage examples for java.util HashSet toArray
<T> T[] toArray(T[] a);
From source file:org.apache.directory.studio.schemaeditor.model.DependenciesComputer.java
/** * Gets the dependencies of the given schema. * * @param schema//from w w w. jav a 2s . c om * the schema * @return * the dependencies of the schema */ @SuppressWarnings("unchecked") public List<Schema> getDependencies(Schema schema) { List<Schema> dependencies = (List<Schema>) schemasDependencies.get(schema); HashSet<Schema> set = new HashSet<Schema>(); if (dependencies != null) { set.addAll(dependencies); } return Arrays.asList(set.toArray(new Schema[0])); }
From source file:com.adobe.cq.wcm.core.components.internal.servlets.ClientLibraryCategoriesDataSourceServlet.java
private List<Resource> getCategoryResourceList(@Nonnull SlingHttpServletRequest request, LibraryType libraryType) {/* w w w. j a v a 2 s . c o m*/ List<Resource> categoryResourceList = new ArrayList<>(); HashSet<String> clientLibraryCategories = new HashSet<String>(); for (ClientLibrary library : htmlLibraryManager.getLibraries().values()) { for (String category : library.getCategories()) { clientLibraryCategories.add(category); } } if (libraryType != null) { Collection<ClientLibrary> clientLibraries = htmlLibraryManager.getLibraries( clientLibraryCategories.toArray(new String[clientLibraryCategories.size()]), libraryType, true, true); clientLibraryCategories.clear(); for (ClientLibrary library : clientLibraries) { for (String category : library.getCategories()) { clientLibraryCategories.add(category); } } } for (String category : clientLibraryCategories) { categoryResourceList.add(new CategoryResource(category, request.getResourceResolver())); } return categoryResourceList; }
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://from w ww . jav a2 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:com.google.sampling.experiential.server.MapServiceImpl.java
/** * @param experimentId/* ww w. ja v a2s .com*/ * @return */ private EventDAO[] getJoinedForExperiment(Long experimentId) { List<EventDAO> eventsForQuery = getEventsForQuery("joined:experimentId=" + experimentId); HashSet<EventDAO> uniqueEvents = new HashSet<EventDAO>(eventsForQuery); EventDAO[] arr = new EventDAO[eventsForQuery.size()]; return uniqueEvents.toArray(arr); }
From source file:org.apache.cocoon.core.container.spring.avalon.PoolableFactoryBean.java
/** * Create a PoolableComponentHandler which manages a pool of Components * created by the specified factory object. * * @param name The name of the bean which should be pooled. *///w w w . java 2s.c om public PoolableFactoryBean(String name, String className, String poolMaxString, Settings settings) throws Exception { String value = poolMaxString; if (settings != null) { value = PropertyHelper.replace(poolMaxString, settings); } int poolMax = Integer.valueOf(value).intValue(); this.name = name; this.max = (poolMax <= 0 ? Integer.MAX_VALUE : poolMax); this.beanClass = Class.forName(className); final HashSet workInterfaces = new HashSet(); // Get *all* interfaces this.guessWorkInterfaces(this.beanClass, workInterfaces); // Add AvalonPoolable workInterfaces.add(AvalonPoolable.class); this.interfaces = (Class[]) workInterfaces.toArray(new Class[workInterfaces.size()]); // Create the pool lists. this.ready = new LinkedList(); }
From source file:org.sleuthkit.hadoop.scoring.CrossImageScoreReducer.java
@Override public void reduce(BytesWritable fileHash, Iterable<BytesWritable> imgIDs, Context context) throws IOException, InterruptedException { boolean inThisImage = false; BytesArrayWritable aw = new BytesArrayWritable(); HashSet<Writable> valueList = new HashSet<Writable>(); for (BytesWritable curImgID : imgIDs) { if (belongsToImage(curImgID.getBytes())) { System.out.println("Hashes equal: " + new String(Hex.encodeHex(curImgID.getBytes())) + " to " + Hex.encodeHexString(ourImageID)); inThisImage = true;/*from ww w . ja va 2 s.c o m*/ } valueList.add(new BytesWritable(curImgID.getBytes().clone())); } if (inThisImage) { aw.set(valueList.toArray(new BytesWritable[0])); context.write(fileHash, aw); System.out.println("Done Writing Context."); } }
From source file:org.droidparts.persist.sql.EntityManager.java
protected String[] getEagerForeignKeyColumnNames() { if (eagerForeignKeyColumnNames == null) { HashSet<String> eagerColumnNames = new HashSet<String>(); for (FieldSpec<ColumnAnn> spec : getTableColumnSpecs(cls)) { if (spec.ann.eager) { eagerColumnNames.add(spec.ann.name); }//from ww w . j a v a 2 s . c o m } eagerForeignKeyColumnNames = eagerColumnNames.toArray(new String[eagerColumnNames.size()]); } return eagerForeignKeyColumnNames; }
From source file:com.act.reachables.Network.java
public static JSONObject get(MongoDB db, Set<Node> nodes, Set<Edge> edges, HashMap<Long, Long> parentIds, HashMap<Long, Edge> toParentEdges) throws JSONException { // init the json object with structure: // {// w w w .ja v a2 s .co m // "name": "nodeid" // "children": [ // { "name": "childnodeid", toparentedge: {}, nodedata:.. }, ... // ] // } HashMap<Long, Node> nodeById = new HashMap<>(); for (Node n : nodes) nodeById.put(n.id, n); HashMap<Long, JSONObject> nodeObjs = new HashMap<>(); // un-deconstruct tree... for (Long nid : parentIds.keySet()) { JSONObject nObj = JSONHelper.nodeObj(db, nodeById.get(nid)); nObj.put("name", nid); if (toParentEdges.get(nid) != null) { JSONObject eObj = JSONHelper.edgeObj(toParentEdges.get(nid), null /* no ordering reqd for referencing nodeMapping */); nObj.put("edge_up", eObj); } else { } nodeObjs.put(nid, nObj); } // now that we know that each node has an associated obj // link the objects together into the tree structure // put each object inside its parent HashSet<Long> unAssignedToParent = new HashSet<>(parentIds.keySet()); for (Long nid : parentIds.keySet()) { JSONObject child = nodeObjs.get(nid); // append child to "children" key within parent JSONObject parent = nodeObjs.get(parentIds.get(nid)); if (parent != null) { parent.append("children", child); unAssignedToParent.remove(nid); } else { } } // outputting a single tree makes front end processing easier // we can always remove the root in the front end and get the forest again // if many trees remain, assuming they indicate a disjoint forest, // add then as child to a proxy root. // if only one tree then return it JSONObject json; if (unAssignedToParent.size() == 0) { json = null; throw new RuntimeException("All nodeMapping have parents! Where is the root? Abort."); } else if (unAssignedToParent.size() == 1) { json = unAssignedToParent.toArray(new JSONObject[0])[0]; // return the only element in the set } else { json = new JSONObject(); for (Long cid : unAssignedToParent) { json.put("name", "root"); json.append("children", nodeObjs.get(cid)); } } return json; }
From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java
public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity, final Action action) { switch (action) { case UPVOTE://from ww w . j a v a 2s. co 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 DELETE: new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm) .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.RedditAction.DELETE); } }).setNegativeButton(R.string.dialog_cancel, null).show(); 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(); LinkHandler.getImageInfo(activity, post.url, Constants.Priority.IMAGE_VIEW, 0, new GetImageInfoListener() { @Override public void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status, final String readableMessage) { final RRError error = General.getGeneralErrorForFailure(activity, type, t, status, post.url); General.showResultDialog(activity, error); } @Override public void onSuccess(final ImgurAPI.ImageInfo info) { CacheManager.getInstance(activity) .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), 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(boolean authorizationInProgress, 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(info.urlOriginal).getPath()); if (dst.exists()) { int count = 0; while (dst.exists()) { count++; dst = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), count + "_" + General.uriFromString(info.urlOriginal) .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()); } }); } @Override public void onNotAnImage() { General.quickToast(activity, R.string.selected_link_is_not_image); } }); 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.getFragmentManager(), null); 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:calliope.db.MongoConnection.java
/** * List all the documents in a Mongo collection * @param collName the name of the collection * @return a String array of document keys * @throws AeseException /*w w w . j a v a2 s .c o m*/ */ @Override public String[] listCollection(String collName) throws AeseException { if (!collName.equals(Database.CORPIX)) { try { connect(); } catch (Exception e) { throw new AeseException(e); } DBCollection coll = getCollectionFromName(collName); BasicDBObject keys = new BasicDBObject(); keys.put(JSONKeys.DOCID, 1); DBCursor cursor = coll.find(new BasicDBObject(), keys); System.out.println("Found " + cursor.count() + " documents"); cursor.count(); if (cursor.length() > 0) { String[] docs = new String[cursor.length()]; Iterator<DBObject> iter = cursor.iterator(); int i = 0; while (iter.hasNext()) docs[i++] = (String) iter.next().get(JSONKeys.DOCID); return docs; } else { return new String[0]; } } else { GridFS gfs = new GridFS(db, collName); DBCursor curs = gfs.getFileList(); int i = 0; List<DBObject> list = curs.toArray(); HashSet<String> set = new HashSet<String>(); Iterator<DBObject> iter = list.iterator(); while (iter.hasNext()) { String name = (String) iter.next().get("filename"); set.add(name); } String[] docs = new String[set.size()]; set.toArray(docs); return docs; } }